This commit is contained in:
Jerry Turcios 2018-10-29 21:09:25 -04:00
commit 3896e3b593
36 changed files with 252 additions and 811 deletions

View File

@ -42,6 +42,7 @@
#endif #endif
#include <algorithm> #include <algorithm>
#include <memory>
#include <string> #include <string>
#include <utility> #include <utility>
@ -346,9 +347,7 @@ class ActionInterface {
// An Action<F> is a copyable and IMMUTABLE (except by assignment) // An Action<F> is a copyable and IMMUTABLE (except by assignment)
// object that represents an action to be taken when a mock function // object that represents an action to be taken when a mock function
// of type F is called. The implementation of Action<T> is just a // of type F is called. The implementation of Action<T> is just a
// linked_ptr to const ActionInterface<T>, so copying is fairly cheap. // std::shared_ptr to const ActionInterface<T>. Don't inherit from Action!
// Don't inherit from Action!
//
// You can view an object implementing ActionInterface<F> as a // You can view an object implementing ActionInterface<F> as a
// concrete action (including its current state), and an Action<F> // concrete action (including its current state), and an Action<F>
// object as a handle to it. // object as a handle to it.
@ -425,7 +424,7 @@ class Action {
#if GTEST_LANG_CXX11 #if GTEST_LANG_CXX11
::std::function<F> fun_; ::std::function<F> fun_;
#endif #endif
internal::linked_ptr<ActionInterface<F> > impl_; std::shared_ptr<ActionInterface<F>> impl_;
}; };
// The PolymorphicAction class template makes it easy to implement a // The PolymorphicAction class template makes it easy to implement a
@ -519,7 +518,7 @@ class ActionAdaptor : public ActionInterface<F1> {
} }
private: private:
const internal::linked_ptr<ActionInterface<F2> > impl_; const std::shared_ptr<ActionInterface<F2>> impl_;
GTEST_DISALLOW_ASSIGN_(ActionAdaptor); GTEST_DISALLOW_ASSIGN_(ActionAdaptor);
}; };
@ -601,7 +600,7 @@ class ReturnAction {
// Result to call. ImplicitCast_ forces the compiler to convert R to // Result to call. ImplicitCast_ forces the compiler to convert R to
// Result without considering explicit constructors, thus resolving the // Result without considering explicit constructors, thus resolving the
// ambiguity. value_ is then initialized using its copy constructor. // ambiguity. value_ is then initialized using its copy constructor.
explicit Impl(const linked_ptr<R>& value) explicit Impl(const std::shared_ptr<R>& value)
: value_before_cast_(*value), : value_before_cast_(*value),
value_(ImplicitCast_<Result>(value_before_cast_)) {} value_(ImplicitCast_<Result>(value_before_cast_)) {}
@ -626,7 +625,7 @@ class ReturnAction {
typedef typename Function<F>::Result Result; typedef typename Function<F>::Result Result;
typedef typename Function<F>::ArgumentTuple ArgumentTuple; typedef typename Function<F>::ArgumentTuple ArgumentTuple;
explicit Impl(const linked_ptr<R>& wrapper) explicit Impl(const std::shared_ptr<R>& wrapper)
: performed_(false), wrapper_(wrapper) {} : performed_(false), wrapper_(wrapper) {}
virtual Result Perform(const ArgumentTuple&) { virtual Result Perform(const ArgumentTuple&) {
@ -638,12 +637,12 @@ class ReturnAction {
private: private:
bool performed_; bool performed_;
const linked_ptr<R> wrapper_; const std::shared_ptr<R> wrapper_;
GTEST_DISALLOW_ASSIGN_(Impl); GTEST_DISALLOW_ASSIGN_(Impl);
}; };
const linked_ptr<R> value_; const std::shared_ptr<R> value_;
GTEST_DISALLOW_ASSIGN_(ReturnAction); GTEST_DISALLOW_ASSIGN_(ReturnAction);
}; };
@ -866,7 +865,7 @@ class SetArgumentPointeeAction<N, Proto, true> {
} }
private: private:
const internal::linked_ptr<Proto> proto_; const std::shared_ptr<Proto> proto_;
GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction); GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction);
}; };
@ -931,7 +930,7 @@ class InvokeCallbackWithoutArgsAction {
Result Perform(const ArgumentTuple&) const { return callback_->Run(); } Result Perform(const ArgumentTuple&) const { return callback_->Run(); }
private: private:
const internal::linked_ptr<CallbackType> callback_; const std::shared_ptr<CallbackType> callback_;
GTEST_DISALLOW_ASSIGN_(InvokeCallbackWithoutArgsAction); GTEST_DISALLOW_ASSIGN_(InvokeCallbackWithoutArgsAction);
}; };

View File

@ -40,6 +40,7 @@
#define GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
#include <limits.h> #include <limits.h>
#include <memory>
#include <ostream> // NOLINT #include <ostream> // NOLINT
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
@ -81,9 +82,8 @@ class CardinalityInterface {
// A Cardinality is a copyable and IMMUTABLE (except by assignment) // A Cardinality is a copyable and IMMUTABLE (except by assignment)
// object that specifies how many times a mock function is expected to // object that specifies how many times a mock function is expected to
// be called. The implementation of Cardinality is just a linked_ptr // be called. The implementation of Cardinality is just a std::shared_ptr
// to const CardinalityInterface, so copying is fairly cheap. // to const CardinalityInterface. Don't inherit from Cardinality!
// Don't inherit from Cardinality!
class GTEST_API_ Cardinality { class GTEST_API_ Cardinality {
public: public:
// Constructs a null cardinality. Needed for storing Cardinality // Constructs a null cardinality. Needed for storing Cardinality
@ -123,7 +123,7 @@ class GTEST_API_ Cardinality {
::std::ostream* os); ::std::ostream* os);
private: private:
internal::linked_ptr<const CardinalityInterface> impl_; std::shared_ptr<const CardinalityInterface> impl_;
}; };
// Creates a cardinality that allows at least n calls. // Creates a cardinality that allows at least n calls.

View File

@ -41,6 +41,7 @@
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
#include <memory>
#include <utility> #include <utility>
#include "gmock/gmock-actions.h" #include "gmock/gmock-actions.h"
@ -348,7 +349,7 @@ class InvokeCallbackAction {
callback_.get(), args); callback_.get(), args);
} }
private: private:
const linked_ptr<CallbackType> callback_; const std::shared_ptr<CallbackType> callback_;
}; };
// An INTERNAL macro for extracting the type of a tuple field. It's // An INTERNAL macro for extracting the type of a tuple field. It's

View File

@ -43,6 +43,7 @@ $$}} This meta comment fixes auto-indentation in editors.
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
#include <memory>
#include <utility> #include <utility>
#include "gmock/gmock-actions.h" #include "gmock/gmock-actions.h"
@ -118,7 +119,7 @@ class InvokeCallbackAction {
callback_.get(), args); callback_.get(), args);
} }
private: private:
const linked_ptr<CallbackType> callback_; const std::shared_ptr<CallbackType> callback_;
}; };
// An INTERNAL macro for extracting the type of a tuple field. It's // An INTERNAL macro for extracting the type of a tuple field. It's

View File

@ -43,14 +43,15 @@
#include <algorithm> #include <algorithm>
#include <iterator> #include <iterator>
#include <limits> #include <limits>
#include <memory>
#include <ostream> // NOLINT #include <ostream> // NOLINT
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <utility> #include <utility>
#include <vector> #include <vector>
#include "gtest/gtest.h"
#include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-internal-utils.h"
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
#if GTEST_HAS_STD_INITIALIZER_LIST_ #if GTEST_HAS_STD_INITIALIZER_LIST_
# include <initializer_list> // NOLINT -- must be after gtest.h # include <initializer_list> // NOLINT -- must be after gtest.h
@ -338,29 +339,15 @@ class MatcherBase {
virtual ~MatcherBase() {} virtual ~MatcherBase() {}
private: private:
// shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar std::shared_ptr<const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)>> impl_;
// interfaces. The former dynamically allocates a chunk of memory
// to hold the reference count, while the latter tracks all
// references using a circular linked list without allocating
// memory. It has been observed that linked_ptr performs better in
// typical scenarios. However, shared_ptr can out-perform
// linked_ptr when there are many more uses of the copy constructor
// than the default constructor.
//
// If performance becomes a problem, we should see if using
// shared_ptr helps.
::testing::internal::linked_ptr<
const MatcherInterface<GTEST_REFERENCE_TO_CONST_(T)> >
impl_;
}; };
} // namespace internal } // namespace internal
// A Matcher<T> is a copyable and IMMUTABLE (except by assignment) // A Matcher<T> is a copyable and IMMUTABLE (except by assignment)
// object that can check whether a value of type T matches. The // object that can check whether a value of type T matches. The
// implementation of Matcher<T> is just a linked_ptr to const // implementation of Matcher<T> is just a std::shared_ptr to const
// MatcherInterface<T>, so copying is fairly cheap. Don't inherit // MatcherInterface<T>. Don't inherit from Matcher!
// from Matcher!
template <typename T> template <typename T>
class Matcher : public internal::MatcherBase<T> { class Matcher : public internal::MatcherBase<T> {
public: public:
@ -1586,7 +1573,7 @@ class MatchesRegexMatcher {
} }
private: private:
const internal::linked_ptr<const RE> regex_; const std::shared_ptr<const RE> regex_;
const bool full_match_; const bool full_match_;
GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher); GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher);

View File

@ -62,6 +62,7 @@
#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
#include <map> #include <map>
#include <memory>
#include <set> #include <set>
#include <sstream> #include <sstream>
#include <string> #include <string>
@ -219,8 +220,7 @@ class GTEST_API_ UntypedFunctionMockerBase {
protected: protected:
typedef std::vector<const void*> UntypedOnCallSpecs; typedef std::vector<const void*> UntypedOnCallSpecs;
typedef std::vector<internal::linked_ptr<ExpectationBase> > using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
UntypedExpectations;
// Returns an Expectation object that references and co-owns exp, // Returns an Expectation object that references and co-owns exp,
// which must be an expectation on this mock function. // which must be an expectation on this mock function.
@ -498,12 +498,7 @@ class GTEST_API_ Mock {
// - Constness is shallow: a const Expectation object itself cannot // - Constness is shallow: a const Expectation object itself cannot
// be modified, but the mutable methods of the ExpectationBase // be modified, but the mutable methods of the ExpectationBase
// object it references can be called via expectation_base(). // object it references can be called via expectation_base().
// - The constructors and destructor are defined out-of-line because
// the Symbian WINSCW compiler wants to otherwise instantiate them
// when it sees this class definition, at which point it doesn't have
// ExpectationBase available yet, leading to incorrect destruction
// in the linked_ptr (or compilation errors if using a checking
// linked_ptr).
class GTEST_API_ Expectation { class GTEST_API_ Expectation {
public: public:
// Constructs a null object that doesn't reference any expectation. // Constructs a null object that doesn't reference any expectation.
@ -555,16 +550,15 @@ class GTEST_API_ Expectation {
typedef ::std::set<Expectation, Less> Set; typedef ::std::set<Expectation, Less> Set;
Expectation( Expectation(
const internal::linked_ptr<internal::ExpectationBase>& expectation_base); const std::shared_ptr<internal::ExpectationBase>& expectation_base);
// Returns the expectation this object references. // Returns the expectation this object references.
const internal::linked_ptr<internal::ExpectationBase>& const std::shared_ptr<internal::ExpectationBase>& expectation_base() const {
expectation_base() const {
return expectation_base_; return expectation_base_;
} }
// A linked_ptr that co-owns the expectation this handle references. // A shared_ptr that co-owns the expectation this handle references.
internal::linked_ptr<internal::ExpectationBase> expectation_base_; std::shared_ptr<internal::ExpectationBase> expectation_base_;
}; };
// A set of expectation handles. Useful in the .After() clause of // A set of expectation handles. Useful in the .After() clause of
@ -646,11 +640,8 @@ class GTEST_API_ Sequence {
void AddExpectation(const Expectation& expectation) const; void AddExpectation(const Expectation& expectation) const;
private: private:
// The last expectation in this sequence. We use a linked_ptr here // The last expectation in this sequence.
// because Sequence objects are copyable and we want the copies to std::shared_ptr<Expectation> last_expectation_;
// be aliases. The linked_ptr allows the copies to co-own and share
// the same Expectation object.
internal::linked_ptr<Expectation> last_expectation_;
}; // class Sequence }; // class Sequence
// An object of this type causes all EXPECT_CALL() statements // An object of this type causes all EXPECT_CALL() statements
@ -873,7 +864,7 @@ class GTEST_API_ ExpectationBase {
Cardinality cardinality_; // The cardinality of the expectation. Cardinality cardinality_; // The cardinality of the expectation.
// The immediate pre-requisites (i.e. expectations that must be // The immediate pre-requisites (i.e. expectations that must be
// satisfied before this expectation can be matched) of this // satisfied before this expectation can be matched) of this
// expectation. We use linked_ptr in the set because we want an // expectation. We use std::shared_ptr in the set because we want an
// Expectation object to be co-owned by its FunctionMocker and its // Expectation object to be co-owned by its FunctionMocker and its
// successors. This allows multiple mock objects to be deleted at // successors. This allows multiple mock objects to be deleted at
// different times. // different times.
@ -1631,7 +1622,7 @@ class FunctionMockerBase : public UntypedFunctionMockerBase {
Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line); Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
TypedExpectation<F>* const expectation = TypedExpectation<F>* const expectation =
new TypedExpectation<F>(this, file, line, source_text, m); new TypedExpectation<F>(this, file, line, source_text, m);
const linked_ptr<ExpectationBase> untyped_expectation(expectation); const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);
// See the definition of untyped_expectations_ for why access to // See the definition of untyped_expectations_ for why access to
// it is unprotected here. // it is unprotected here.
untyped_expectations_.push_back(untyped_expectation); untyped_expectations_.push_back(untyped_expectation);
@ -1914,7 +1905,8 @@ GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
// failure to disambiguate two overloads of this method in the ON_CALL statement // failure to disambiguate two overloads of this method in the ON_CALL statement
// is how we block callers from setting expectations on overloaded methods. // is how we block callers from setting expectations on overloaded methods.
#define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \ #define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), NULL) \ ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
nullptr) \
.Setter(__FILE__, __LINE__, #mock_expr, #call) .Setter(__FILE__, __LINE__, #mock_expr, #call)
#define ON_CALL(obj, call) \ #define ON_CALL(obj, call) \

View File

@ -92,15 +92,6 @@ inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {
template <typename Element> template <typename Element>
inline Element* GetRawPointer(Element* p) { return p; } inline Element* GetRawPointer(Element* p) { return p; }
// This comparator allows linked_ptr to be stored in sets.
template <typename T>
struct LinkedPtrLessThan {
bool operator()(const ::testing::internal::linked_ptr<T>& lhs,
const ::testing::internal::linked_ptr<T>& rhs) const {
return lhs.get() < rhs.get();
}
};
// Symbian compilation can be done with wchar_t being either a native // Symbian compilation can be done with wchar_t being either a native
// type or a typedef. Using Google Mock with OpenC without wchar_t // type or a typedef. Using Google Mock with OpenC without wchar_t
// should require the definition of _STLP_NO_WCHAR_T. // should require the definition of _STLP_NO_WCHAR_T.

View File

@ -52,7 +52,6 @@
// here, as Google Mock depends on Google Test. Only add a utility // here, as Google Mock depends on Google Test. Only add a utility
// here if it's truly specific to Google Mock. // here if it's truly specific to Google Mock.
#include "gtest/internal/gtest-linked_ptr.h"
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#include "gmock/internal/custom/gmock-port.h" #include "gmock/internal/custom/gmock-port.h"

View File

@ -38,6 +38,7 @@
#include <stdlib.h> #include <stdlib.h>
#include <iostream> // NOLINT #include <iostream> // NOLINT
#include <map> #include <map>
#include <memory>
#include <set> #include <set>
#include <string> #include <string>
#include <vector> #include <vector>
@ -848,7 +849,7 @@ void Mock::ClearDefaultActionsLocked(void* mock_obj)
Expectation::Expectation() {} Expectation::Expectation() {}
Expectation::Expectation( Expectation::Expectation(
const internal::linked_ptr<internal::ExpectationBase>& an_expectation_base) const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)
: expectation_base_(an_expectation_base) {} : expectation_base_(an_expectation_base) {}
Expectation::~Expectation() {} Expectation::~Expectation() {}
@ -866,7 +867,7 @@ void Sequence::AddExpectation(const Expectation& expectation) const {
// Creates the implicit sequence if there isn't one. // Creates the implicit sequence if there isn't one.
InSequence::InSequence() { InSequence::InSequence() {
if (internal::g_gmock_implicit_sequence.get() == NULL) { if (internal::g_gmock_implicit_sequence.get() == nullptr) {
internal::g_gmock_implicit_sequence.set(new Sequence); internal::g_gmock_implicit_sequence.set(new Sequence);
sequence_created_ = true; sequence_created_ = true;
} else { } else {
@ -879,7 +880,7 @@ InSequence::InSequence() {
InSequence::~InSequence() { InSequence::~InSequence() {
if (sequence_created_) { if (sequence_created_) {
delete internal::g_gmock_implicit_sequence.get(); delete internal::g_gmock_implicit_sequence.get();
internal::g_gmock_implicit_sequence.set(NULL); internal::g_gmock_implicit_sequence.set(nullptr);
} }
} }

View File

@ -35,6 +35,7 @@
#include "gmock/gmock-generated-actions.h" #include "gmock/gmock-generated-actions.h"
#include <functional> #include <functional>
#include <memory>
#include <sstream> #include <sstream>
#include <string> #include <string>
#include "gmock/gmock.h" #include "gmock/gmock.h"
@ -1129,9 +1130,9 @@ ACTION_TEMPLATE(ReturnSmartPointer,
} }
TEST(ActionTemplateTest, WorksForTemplateTemplateParameters) { TEST(ActionTemplateTest, WorksForTemplateTemplateParameters) {
using ::testing::internal::linked_ptr; const Action<std::shared_ptr<int>()> a =
const Action<linked_ptr<int>()> a = ReturnSmartPointer<linked_ptr>(42); ReturnSmartPointer<std::shared_ptr>(42);
linked_ptr<int> p = a.Perform(std::make_tuple()); std::shared_ptr<int> p = a.Perform(std::make_tuple());
EXPECT_EQ(42, *p); EXPECT_EQ(42, *p);
} }
@ -1161,11 +1162,10 @@ ACTION_TEMPLATE(ReturnGiant,
} }
TEST(ActionTemplateTest, WorksFor10TemplateParameters) { TEST(ActionTemplateTest, WorksFor10TemplateParameters) {
using ::testing::internal::linked_ptr; using Giant = GiantTemplate<std::shared_ptr<int>, bool, double, 5, true, 6,
typedef GiantTemplate<linked_ptr<int>, bool, double, 5, char, unsigned, int>;
true, 6, char, unsigned, int> Giant; const Action<Giant()> a = ReturnGiant<int, bool, double, 5, true, 6, char,
const Action<Giant()> a = ReturnGiant< unsigned, int, std::shared_ptr>(42);
int, bool, double, 5, true, 6, char, unsigned, int, linked_ptr>(42);
Giant giant = a.Perform(std::make_tuple()); Giant giant = a.Perform(std::make_tuple());
EXPECT_EQ(42, giant.value); EXPECT_EQ(42, giant.value);
} }

View File

@ -224,8 +224,8 @@ TEST_F(FunctionMockerTest, MocksBinaryFunction) {
// Tests mocking a decimal function. // Tests mocking a decimal function.
TEST_F(FunctionMockerTest, MocksDecimalFunction) { TEST_F(FunctionMockerTest, MocksDecimalFunction) {
EXPECT_CALL(mock_foo_, Decimal(true, 'a', 0, 0, 1L, A<float>(), EXPECT_CALL(mock_foo_, Decimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U,
Lt(100), 5U, NULL, "hi")) nullptr, "hi"))
.WillOnce(Return(5)); .WillOnce(Return(5));
EXPECT_EQ(5, foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi")); EXPECT_EQ(5, foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi"));
@ -326,11 +326,11 @@ TEST_F(FunctionMockerTest, MocksUnaryFunctionWithCallType) {
// Tests mocking a decimal function with calltype. // Tests mocking a decimal function with calltype.
TEST_F(FunctionMockerTest, MocksDecimalFunctionWithCallType) { TEST_F(FunctionMockerTest, MocksDecimalFunctionWithCallType) {
EXPECT_CALL(mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(), EXPECT_CALL(mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U,
Lt(100), 5U, NULL, "hi")) nullptr, "hi"))
.WillOnce(Return(10)); .WillOnce(Return(10));
EXPECT_EQ(10, foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, "hi")); EXPECT_EQ(10, foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, "hi"));
} }
// Tests mocking functions overloaded on the const-ness of this object. // Tests mocking functions overloaded on the const-ness of this object.

View File

@ -123,8 +123,6 @@ TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) {
} }
TEST(PointeeOfTest, WorksForSmartPointers) { TEST(PointeeOfTest, WorksForSmartPointers) {
CompileAssertTypesEqual<const char,
PointeeOf<internal::linked_ptr<const char> >::type>();
#if GTEST_HAS_STD_UNIQUE_PTR_ #if GTEST_HAS_STD_UNIQUE_PTR_
CompileAssertTypesEqual<int, PointeeOf<std::unique_ptr<int> >::type>(); CompileAssertTypesEqual<int, PointeeOf<std::unique_ptr<int> >::type>();
#endif // GTEST_HAS_STD_UNIQUE_PTR_ #endif // GTEST_HAS_STD_UNIQUE_PTR_
@ -151,10 +149,6 @@ TEST(GetRawPointerTest, WorksForSmartPointers) {
const std::shared_ptr<double> p2(raw_p2); const std::shared_ptr<double> p2(raw_p2);
EXPECT_EQ(raw_p2, GetRawPointer(p2)); EXPECT_EQ(raw_p2, GetRawPointer(p2));
#endif // GTEST_HAS_STD_SHARED_PTR_ #endif // GTEST_HAS_STD_SHARED_PTR_
const char* const raw_p4 = new const char('a'); // NOLINT
const internal::linked_ptr<const char> p4(raw_p4);
EXPECT_EQ(raw_p4, GetRawPointer(p4));
} }
TEST(GetRawPointerTest, WorksForRawPointers) { TEST(GetRawPointerTest, WorksForRawPointers) {
@ -687,7 +681,7 @@ TEST(StlContainerViewTest, WorksForDynamicNativeArray) {
StlContainerView<std::tuple<const int*, size_t> >::type>(); StlContainerView<std::tuple<const int*, size_t> >::type>();
StaticAssertTypeEq< StaticAssertTypeEq<
NativeArray<double>, NativeArray<double>,
StlContainerView<std::tuple<linked_ptr<double>, int> >::type>(); StlContainerView<std::tuple<std::shared_ptr<double>, int> >::type>();
StaticAssertTypeEq< StaticAssertTypeEq<
const NativeArray<int>, const NativeArray<int>,

View File

@ -143,13 +143,11 @@ using testing::internal::ExplainMatchFailureTupleTo;
using testing::internal::FloatingEqMatcher; using testing::internal::FloatingEqMatcher;
using testing::internal::FormatMatcherDescription; using testing::internal::FormatMatcherDescription;
using testing::internal::IsReadableTypeName; using testing::internal::IsReadableTypeName;
using testing::internal::linked_ptr;
using testing::internal::MatchMatrix; using testing::internal::MatchMatrix;
using testing::internal::RE; using testing::internal::RE;
using testing::internal::scoped_ptr; using testing::internal::scoped_ptr;
using testing::internal::StreamMatchResultListener; using testing::internal::StreamMatchResultListener;
using testing::internal::Strings; using testing::internal::Strings;
using testing::internal::linked_ptr;
using testing::internal::scoped_ptr; using testing::internal::scoped_ptr;
using testing::internal::string; using testing::internal::string;
@ -323,7 +321,7 @@ TEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {
// Tests that NULL can be used in place of Eq(NULL). // Tests that NULL can be used in place of Eq(NULL).
TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) { TEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {
Matcher<int*> m1 = NULL; Matcher<int*> m1 = nullptr;
EXPECT_TRUE(m1.Matches(nullptr)); EXPECT_TRUE(m1.Matches(nullptr));
int n = 0; int n = 0;
EXPECT_FALSE(m1.Matches(&n)); EXPECT_FALSE(m1.Matches(&n));
@ -1177,24 +1175,6 @@ TEST(IsNullTest, MatchesNullPointer) {
#endif #endif
} }
TEST(IsNullTest, LinkedPtr) {
const Matcher<linked_ptr<int> > m = IsNull();
const linked_ptr<int> null_p;
const linked_ptr<int> non_null_p(new int);
EXPECT_TRUE(m.Matches(null_p));
EXPECT_FALSE(m.Matches(non_null_p));
}
TEST(IsNullTest, ReferenceToConstLinkedPtr) {
const Matcher<const linked_ptr<double>&> m = IsNull();
const linked_ptr<double> null_p;
const linked_ptr<double> non_null_p(new double);
EXPECT_TRUE(m.Matches(null_p));
EXPECT_FALSE(m.Matches(non_null_p));
}
#if GTEST_LANG_CXX11 #if GTEST_LANG_CXX11
TEST(IsNullTest, StdFunction) { TEST(IsNullTest, StdFunction) {
const Matcher<std::function<void()>> m = IsNull(); const Matcher<std::function<void()>> m = IsNull();
@ -1226,18 +1206,18 @@ TEST(NotNullTest, MatchesNonNullPointer) {
} }
TEST(NotNullTest, LinkedPtr) { TEST(NotNullTest, LinkedPtr) {
const Matcher<linked_ptr<int> > m = NotNull(); const Matcher<std::shared_ptr<int>> m = NotNull();
const linked_ptr<int> null_p; const std::shared_ptr<int> null_p;
const linked_ptr<int> non_null_p(new int); const std::shared_ptr<int> non_null_p(new int);
EXPECT_FALSE(m.Matches(null_p)); EXPECT_FALSE(m.Matches(null_p));
EXPECT_TRUE(m.Matches(non_null_p)); EXPECT_TRUE(m.Matches(non_null_p));
} }
TEST(NotNullTest, ReferenceToConstLinkedPtr) { TEST(NotNullTest, ReferenceToConstLinkedPtr) {
const Matcher<const linked_ptr<double>&> m = NotNull(); const Matcher<const std::shared_ptr<double>&> m = NotNull();
const linked_ptr<double> null_p; const std::shared_ptr<double> null_p;
const linked_ptr<double> non_null_p(new double); const std::shared_ptr<double> non_null_p(new double);
EXPECT_FALSE(m.Matches(null_p)); EXPECT_FALSE(m.Matches(null_p));
EXPECT_TRUE(m.Matches(non_null_p)); EXPECT_TRUE(m.Matches(non_null_p));
@ -4779,8 +4759,8 @@ TEST(IsTrueTest, IsTrueIsFalse) {
EXPECT_THAT(false, Not(IsTrue())); EXPECT_THAT(false, Not(IsTrue()));
EXPECT_THAT(0, Not(IsTrue())); EXPECT_THAT(0, Not(IsTrue()));
EXPECT_THAT(0, IsFalse()); EXPECT_THAT(0, IsFalse());
EXPECT_THAT(NULL, Not(IsTrue())); EXPECT_THAT(nullptr, Not(IsTrue()));
EXPECT_THAT(NULL, IsFalse()); EXPECT_THAT(nullptr, IsFalse());
EXPECT_THAT(-1, IsTrue()); EXPECT_THAT(-1, IsTrue());
EXPECT_THAT(-1, Not(IsFalse())); EXPECT_THAT(-1, Not(IsFalse()));
EXPECT_THAT(1, IsTrue()); EXPECT_THAT(1, IsTrue());

View File

@ -35,11 +35,11 @@
#include "gmock/gmock-more-actions.h" #include "gmock/gmock-more-actions.h"
#include <functional> #include <functional>
#include <memory>
#include <sstream> #include <sstream>
#include <string> #include <string>
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gtest/gtest.h" #include "gtest/gtest.h"
#include "gtest/internal/gtest-linked_ptr.h"
namespace testing { namespace testing {
namespace gmock_more_actions_test { namespace gmock_more_actions_test {
@ -61,7 +61,6 @@ using testing::StaticAssertTypeEq;
using testing::Unused; using testing::Unused;
using testing::WithArg; using testing::WithArg;
using testing::WithoutArgs; using testing::WithoutArgs;
using testing::internal::linked_ptr;
// For suppressing compiler warnings on conversion possibly losing precision. // For suppressing compiler warnings on conversion possibly losing precision.
inline short Short(short n) { return n; } // NOLINT inline short Short(short n) { return n; } // NOLINT
@ -529,14 +528,6 @@ TEST(SaveArgPointeeActionTest, WorksForCompatibleType) {
EXPECT_EQ('a', result); EXPECT_EQ('a', result);
} }
TEST(SaveArgPointeeActionTest, WorksForLinkedPtr) {
int result = 0;
linked_ptr<int> value(new int(5));
const Action<void(linked_ptr<int>)> a1 = SaveArgPointee<0>(&result);
a1.Perform(std::make_tuple(value));
EXPECT_EQ(5, result);
}
TEST(SetArgRefereeActionTest, WorksForSameType) { TEST(SetArgRefereeActionTest, WorksForSameType) {
int value = 0; int value = 0;
const Action<void(int&)> a1 = SetArgReferee<0>(1); const Action<void(int&)> a1 = SetArgReferee<0>(1);

View File

@ -34,6 +34,7 @@
#include "gmock/gmock-spec-builders.h" #include "gmock/gmock-spec-builders.h"
#include <memory>
#include <ostream> // NOLINT #include <ostream> // NOLINT
#include <sstream> #include <sstream>
#include <string> #include <string>
@ -99,7 +100,6 @@ using testing::internal::kFail;
using testing::internal::kInfoVerbosity; using testing::internal::kInfoVerbosity;
using testing::internal::kWarn; using testing::internal::kWarn;
using testing::internal::kWarningVerbosity; using testing::internal::kWarningVerbosity;
using testing::internal::linked_ptr;
#if GTEST_HAS_STREAM_REDIRECTION #if GTEST_HAS_STREAM_REDIRECTION
using testing::HasSubstr; using testing::HasSubstr;
@ -172,7 +172,7 @@ class ReferenceHoldingMock {
public: public:
ReferenceHoldingMock() {} ReferenceHoldingMock() {}
MOCK_METHOD1(AcceptReference, void(linked_ptr<MockA>*)); MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*));
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(ReferenceHoldingMock); GTEST_DISALLOW_COPY_AND_ASSIGN_(ReferenceHoldingMock);
@ -2619,7 +2619,7 @@ TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
TEST(VerifyAndClearTest, TEST(VerifyAndClearTest,
DestroyingChainedMocksDoesNotDeadlockThroughExpectations) { DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {
linked_ptr<MockA> a(new MockA); std::shared_ptr<MockA> a(new MockA);
ReferenceHoldingMock test_mock; ReferenceHoldingMock test_mock;
// EXPECT_CALL stores a reference to a inside test_mock. // EXPECT_CALL stores a reference to a inside test_mock.
@ -2639,7 +2639,7 @@ TEST(VerifyAndClearTest,
TEST(VerifyAndClearTest, TEST(VerifyAndClearTest,
DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) { DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {
linked_ptr<MockA> a(new MockA); std::shared_ptr<MockA> a(new MockA);
ReferenceHoldingMock test_mock; ReferenceHoldingMock test_mock;
// ON_CALL stores a reference to a inside test_mock. // ON_CALL stores a reference to a inside test_mock.

View File

@ -414,7 +414,7 @@ TEST(LinkTest, TestThrow) {
Mock mock; Mock mock;
EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Throw(42)); EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Throw(42));
EXPECT_THROW(mock.VoidFromString(NULL), int); EXPECT_THROW(mock.VoidFromString(nullptr), int);
} }
#endif // GTEST_HAS_EXCEPTIONS #endif // GTEST_HAS_EXCEPTIONS

View File

@ -60,87 +60,8 @@ void JoinAndDelete(ThreadWithParam<T>* t) {
delete t; delete t;
} }
using internal::linked_ptr;
// Helper classes for testing using linked_ptr concurrently.
class Base {
public:
explicit Base(int a_x) : x_(a_x) {}
virtual ~Base() {}
int x() const { return x_; }
private:
int x_;
};
class Derived1 : public Base {
public:
Derived1(int a_x, int a_y) : Base(a_x), y_(a_y) {}
int y() const { return y_; }
private:
int y_;
};
class Derived2 : public Base {
public:
Derived2(int a_x, int a_z) : Base(a_x), z_(a_z) {}
int z() const { return z_; }
private:
int z_;
};
linked_ptr<Derived1> pointer1(new Derived1(1, 2));
linked_ptr<Derived2> pointer2(new Derived2(3, 4));
struct Dummy {}; struct Dummy {};
// Tests that we can copy from a linked_ptr and read it concurrently.
void TestConcurrentCopyAndReadLinkedPtr(Dummy /* dummy */) {
// Reads pointer1 and pointer2 while they are being copied from in
// another thread.
EXPECT_EQ(1, pointer1->x());
EXPECT_EQ(2, pointer1->y());
EXPECT_EQ(3, pointer2->x());
EXPECT_EQ(4, pointer2->z());
// Copies from pointer1.
linked_ptr<Derived1> p1(pointer1);
EXPECT_EQ(1, p1->x());
EXPECT_EQ(2, p1->y());
// Assigns from pointer2 where the LHS was empty.
linked_ptr<Base> p2;
p2 = pointer1;
EXPECT_EQ(1, p2->x());
// Assigns from pointer2 where the LHS was not empty.
p2 = pointer2;
EXPECT_EQ(3, p2->x());
}
const linked_ptr<Derived1> p0(new Derived1(1, 2));
// Tests that we can concurrently modify two linked_ptrs that point to
// the same object.
void TestConcurrentWriteToEqualLinkedPtr(Dummy /* dummy */) {
// p1 and p2 point to the same, shared thing. One thread resets p1.
// Another thread assigns to p2. This will cause the same
// underlying "ring" to be updated concurrently.
linked_ptr<Derived1> p1(p0);
linked_ptr<Derived1> p2(p0);
EXPECT_EQ(1, p1->x());
EXPECT_EQ(2, p1->y());
EXPECT_EQ(1, p2->x());
EXPECT_EQ(2, p2->y());
p1.reset();
p2 = p0;
EXPECT_EQ(1, p2->x());
EXPECT_EQ(2, p2->y());
}
// Tests that different mock objects can be used in their respective // Tests that different mock objects can be used in their respective
// threads. This should generate no Google Test failure. // threads. This should generate no Google Test failure.
@ -275,8 +196,6 @@ void TestPartiallyOrderedExpectationsWithThreads(Dummy /* dummy */) {
// Tests using Google Mock constructs in many threads concurrently. // Tests using Google Mock constructs in many threads concurrently.
TEST(StressTest, CanUseGMockWithThreads) { TEST(StressTest, CanUseGMockWithThreads) {
void (*test_routines[])(Dummy dummy) = { void (*test_routines[])(Dummy dummy) = {
&TestConcurrentCopyAndReadLinkedPtr,
&TestConcurrentWriteToEqualLinkedPtr,
&TestConcurrentMockObjects, &TestConcurrentMockObjects,
&TestConcurrentCallsOnSameObject, &TestConcurrentCallsOnSameObject,
&TestPartiallyOrderedExpectationsWithThreads, &TestPartiallyOrderedExpectationsWithThreads,

View File

@ -195,7 +195,6 @@ $env:Path = \"$project_bin;$env:Path\"
cxx_test(googletest-death-test-test gtest_main) cxx_test(googletest-death-test-test gtest_main)
cxx_test(gtest_environment_test gtest) cxx_test(gtest_environment_test gtest)
cxx_test(googletest-filepath-test gtest_main) cxx_test(googletest-filepath-test gtest_main)
cxx_test(googletest-linked-ptr-test gtest_main)
cxx_test(googletest-listener-test gtest_main) cxx_test(googletest-listener-test gtest_main)
cxx_test(gtest_main_unittest gtest_main) cxx_test(gtest_main_unittest gtest_main)
cxx_test(googletest-message-test gtest_main) cxx_test(googletest-message-test gtest_main)

View File

@ -48,7 +48,6 @@ EXTRA_DIST += \
test/gtest-death-test_ex_test.cc \ test/gtest-death-test_ex_test.cc \
test/gtest-death-test_test.cc \ test/gtest-death-test_test.cc \
test/gtest-filepath_test.cc \ test/gtest-filepath_test.cc \
test/gtest-linked_ptr_test.cc \
test/gtest-listener_test.cc \ test/gtest-listener_test.cc \
test/gtest-message_test.cc \ test/gtest-message_test.cc \
test/gtest-options_test.cc \ test/gtest-options_test.cc \
@ -200,7 +199,6 @@ pkginclude_internal_HEADERS = \
include/gtest/internal/gtest-death-test-internal.h \ include/gtest/internal/gtest-death-test-internal.h \
include/gtest/internal/gtest-filepath.h \ include/gtest/internal/gtest-filepath.h \
include/gtest/internal/gtest-internal.h \ include/gtest/internal/gtest-internal.h \
include/gtest/internal/gtest-linked_ptr.h \
include/gtest/internal/gtest-param-util-generated.h \ include/gtest/internal/gtest-param-util-generated.h \
include/gtest/internal/gtest-param-util.h \ include/gtest/internal/gtest-param-util.h \
include/gtest/internal/gtest-port.h \ include/gtest/internal/gtest-port.h \

View File

@ -207,7 +207,7 @@ class GTEST_API_ Message {
// tr1::type_traits-like is_pointer works, and we can overload on that. // tr1::type_traits-like is_pointer works, and we can overload on that.
template <typename T> template <typename T>
inline void StreamHelper(internal::true_type /*is_pointer*/, T* pointer) { inline void StreamHelper(internal::true_type /*is_pointer*/, T* pointer) {
if (pointer == NULL) { if (pointer == nullptr) {
*ss_ << "(null)"; *ss_ << "(null)";
} else { } else {
*ss_ << pointer; *ss_ << pointer;

View File

@ -1449,6 +1449,13 @@ AssertionResult CmpHelperEQFailure(const char* lhs_expression,
false); false);
} }
// This block of code defines operator==/!=
// to block lexical scope lookup.
// It prevents using invalid operator==/!= defined at namespace scope.
struct faketype {};
inline bool operator==(faketype, faketype) { return true; }
inline bool operator!=(faketype, faketype) { return false; }
// The helper function for {ASSERT|EXPECT}_EQ. // The helper function for {ASSERT|EXPECT}_EQ.
template <typename T1, typename T2> template <typename T1, typename T2>
AssertionResult CmpHelperEQ(const char* lhs_expression, AssertionResult CmpHelperEQ(const char* lhs_expression,

View File

@ -191,11 +191,11 @@ GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
if (::testing::internal::AlwaysTrue()) { \ if (::testing::internal::AlwaysTrue()) { \
const ::testing::internal::RE& gtest_regex = (regex); \ const ::testing::internal::RE& gtest_regex = (regex); \
::testing::internal::DeathTest* gtest_dt; \ ::testing::internal::DeathTest* gtest_dt; \
if (!::testing::internal::DeathTest::Create(#statement, &gtest_regex, \ if (!::testing::internal::DeathTest::Create( \
__FILE__, __LINE__, &gtest_dt)) { \ #statement, &gtest_regex, __FILE__, __LINE__, &gtest_dt)) { \
goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \
} \ } \
if (gtest_dt != NULL) { \ if (gtest_dt != nullptr) { \
::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \ ::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \
gtest_dt_ptr(gtest_dt); \ gtest_dt_ptr(gtest_dt); \
switch (gtest_dt->AssumeRole()) { \ switch (gtest_dt->AssumeRole()) { \
@ -205,8 +205,8 @@ GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
} \ } \
break; \ break; \
case ::testing::internal::DeathTest::EXECUTE_TEST: { \ case ::testing::internal::DeathTest::EXECUTE_TEST: { \
::testing::internal::DeathTest::ReturnSentinel \ ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel( \
gtest_sentinel(gtest_dt); \ gtest_dt); \
GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \ GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \
gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \ gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \
break; \ break; \
@ -216,8 +216,8 @@ GTEST_API_ bool ExitedUnsuccessfully(int exit_status);
} \ } \
} \ } \
} else \ } else \
GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__): \ GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__) \
fail(::testing::internal::DeathTest::LastMessage()) : fail(::testing::internal::DeathTest::LastMessage())
// The symbol "fail" here expands to something into which a message // The symbol "fail" here expands to something into which a message
// can be streamed. // can be streamed.

View File

@ -1401,26 +1401,26 @@ class FlatTuple
// Helper macro for defining tests. // Helper macro for defining tests.
#define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id) \ #define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id) \
class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\ class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \
: public parent_class { \
public: \ public: \
GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \ GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \
\
private: \ private: \
virtual void TestBody(); \ virtual void TestBody(); \
static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \ static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_; \
GTEST_DISALLOW_COPY_AND_ASSIGN_(\ GTEST_DISALLOW_COPY_AND_ASSIGN_(GTEST_TEST_CLASS_NAME_(test_case_name, \
GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\ test_name)); \
}; \ }; \
\ \
::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\ ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, \
::test_info_ =\ test_name)::test_info_ = \
::testing::internal::MakeAndRegisterTestInfo( \ ::testing::internal::MakeAndRegisterTestInfo( \
#test_case_name, #test_name, NULL, NULL, \ #test_case_name, #test_name, nullptr, nullptr, \
::testing::internal::CodeLocation(__FILE__, __LINE__), \ ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id), \
(parent_id), \ parent_class::SetUpTestCase, parent_class::TearDownTestCase, \
parent_class::SetUpTestCase, \ new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_( \
parent_class::TearDownTestCase, \ test_case_name, test_name)>); \
new ::testing::internal::TestFactoryImpl<\
GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\
void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody()
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_

View File

@ -1,243 +0,0 @@
// Copyright 2003 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// A "smart" pointer type with reference tracking. Every pointer to a
// particular object is kept on a circular linked list. When the last pointer
// to an object is destroyed or reassigned, the object is deleted.
//
// Used properly, this deletes the object when the last reference goes away.
// There are several caveats:
// - Like all reference counting schemes, cycles lead to leaks.
// - Each smart pointer is actually two pointers (8 bytes instead of 4).
// - Every time a pointer is assigned, the entire list of pointers to that
// object is traversed. This class is therefore NOT SUITABLE when there
// will often be more than two or three pointers to a particular object.
// - References are only tracked as long as linked_ptr<> objects are copied.
// If a linked_ptr<> is converted to a raw pointer and back, BAD THINGS
// will happen (double deletion).
//
// A good use of this class is storing object references in STL containers.
// You can safely put linked_ptr<> in a vector<>.
// Other uses may not be as good.
//
// Note: If you use an incomplete type with linked_ptr<>, the class
// *containing* linked_ptr<> must have a constructor and destructor (even
// if they do nothing!).
//
// Bill Gibbons suggested we use something like this.
//
// Thread Safety:
// Unlike other linked_ptr implementations, in this implementation
// a linked_ptr object is thread-safe in the sense that:
// - it's safe to copy linked_ptr objects concurrently,
// - it's safe to copy *from* a linked_ptr and read its underlying
// raw pointer (e.g. via get()) concurrently, and
// - it's safe to write to two linked_ptrs that point to the same
// shared object concurrently.
// FIXME: rename this to safe_linked_ptr to avoid
// confusion with normal linked_ptr.
// GOOGLETEST_CM0001 DO NOT DELETE
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_
#include <stdlib.h>
#include <assert.h>
#include "gtest/internal/gtest-port.h"
namespace testing {
namespace internal {
// Protects copying of all linked_ptr objects.
GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_linked_ptr_mutex);
// This is used internally by all instances of linked_ptr<>. It needs to be
// a non-template class because different types of linked_ptr<> can refer to
// the same object (linked_ptr<Superclass>(obj) vs linked_ptr<Subclass>(obj)).
// So, it needs to be possible for different types of linked_ptr to participate
// in the same circular linked list, so we need a single class type here.
//
// DO NOT USE THIS CLASS DIRECTLY YOURSELF. Use linked_ptr<T>.
class linked_ptr_internal {
public:
// Create a new circle that includes only this instance.
void join_new() {
next_ = this;
}
// Many linked_ptr operations may change p.link_ for some linked_ptr
// variable p in the same circle as this object. Therefore we need
// to prevent two such operations from occurring concurrently.
//
// Note that different types of linked_ptr objects can coexist in a
// circle (e.g. linked_ptr<Base>, linked_ptr<Derived1>, and
// linked_ptr<Derived2>). Therefore we must use a single mutex to
// protect all linked_ptr objects. This can create serious
// contention in production code, but is acceptable in a testing
// framework.
// Join an existing circle.
void join(linked_ptr_internal const* ptr)
GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) {
MutexLock lock(&g_linked_ptr_mutex);
linked_ptr_internal const* p = ptr;
while (p->next_ != ptr) {
assert(p->next_ != this &&
"Trying to join() a linked ring we are already in. "
"Is GMock thread safety enabled?");
p = p->next_;
}
p->next_ = this;
next_ = ptr;
}
// Leave whatever circle we're part of. Returns true if we were the
// last member of the circle. Once this is done, you can join() another.
bool depart()
GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) {
MutexLock lock(&g_linked_ptr_mutex);
if (next_ == this) return true;
linked_ptr_internal const* p = next_;
while (p->next_ != this) {
assert(p->next_ != next_ &&
"Trying to depart() a linked ring we are not in. "
"Is GMock thread safety enabled?");
p = p->next_;
}
p->next_ = next_;
return false;
}
private:
mutable linked_ptr_internal const* next_;
};
template <typename T>
class linked_ptr {
public:
typedef T element_type;
// Take over ownership of a raw pointer. This should happen as soon as
// possible after the object is created.
explicit linked_ptr(T* ptr = nullptr) { capture(ptr); }
~linked_ptr() { depart(); }
// Copy an existing linked_ptr<>, adding ourselves to the list of references.
template <typename U> linked_ptr(linked_ptr<U> const& ptr) { copy(&ptr); }
linked_ptr(linked_ptr const& ptr) { // NOLINT
assert(&ptr != this);
copy(&ptr);
}
// Assignment releases the old value and acquires the new.
template <typename U> linked_ptr& operator=(linked_ptr<U> const& ptr) {
depart();
copy(&ptr);
return *this;
}
linked_ptr& operator=(linked_ptr const& ptr) {
if (&ptr != this) {
depart();
copy(&ptr);
}
return *this;
}
// Smart pointer members.
void reset(T* ptr = nullptr) {
depart();
capture(ptr);
}
T* get() const { return value_; }
T* operator->() const { return value_; }
T& operator*() const { return *value_; }
bool operator==(T* p) const { return value_ == p; }
bool operator!=(T* p) const { return value_ != p; }
template <typename U>
bool operator==(linked_ptr<U> const& ptr) const {
return value_ == ptr.get();
}
template <typename U>
bool operator!=(linked_ptr<U> const& ptr) const {
return value_ != ptr.get();
}
private:
template <typename U>
friend class linked_ptr;
T* value_;
linked_ptr_internal link_;
void depart() {
if (link_.depart()) delete value_;
}
void capture(T* ptr) {
value_ = ptr;
link_.join_new();
}
template <typename U> void copy(linked_ptr<U> const* ptr) {
value_ = ptr->get();
if (value_)
link_.join(&ptr->link_);
else
link_.join_new();
}
};
template<typename T> inline
bool operator==(T* ptr, const linked_ptr<T>& x) {
return ptr == x.get();
}
template<typename T> inline
bool operator!=(T* ptr, const linked_ptr<T>& x) {
return ptr != x.get();
}
// A function to convert T* into linked_ptr<T>
// Doing e.g. make_linked_ptr(new FooBarBaz<type>(arg)) is a shorter notation
// for linked_ptr<FooBarBaz<type> >(new FooBarBaz<type>(arg))
template <typename T>
linked_ptr<T> make_linked_ptr(T* ptr) {
return linked_ptr<T>(ptr);
}
} // namespace internal
} // namespace testing
#endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_

View File

@ -47,6 +47,10 @@
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_
#include <cassert>
#include <memory>
#include "gtest/internal/gtest-param-util.h" #include "gtest/internal/gtest-param-util.h"
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
@ -162,7 +166,7 @@ class CartesianProductGenerator2
const typename ParamGenerator<T2>::iterator begin2_; const typename ParamGenerator<T2>::iterator begin2_;
const typename ParamGenerator<T2>::iterator end2_; const typename ParamGenerator<T2>::iterator end2_;
typename ParamGenerator<T2>::iterator current2_; typename ParamGenerator<T2>::iterator current2_;
linked_ptr<ParamType> current_value_; std::shared_ptr<ParamType> current_value_;
}; // class CartesianProductGenerator2::Iterator }; // class CartesianProductGenerator2::Iterator
// No implementation - assignment is unsupported. // No implementation - assignment is unsupported.
@ -293,7 +297,7 @@ class CartesianProductGenerator3
const typename ParamGenerator<T3>::iterator begin3_; const typename ParamGenerator<T3>::iterator begin3_;
const typename ParamGenerator<T3>::iterator end3_; const typename ParamGenerator<T3>::iterator end3_;
typename ParamGenerator<T3>::iterator current3_; typename ParamGenerator<T3>::iterator current3_;
linked_ptr<ParamType> current_value_; std::shared_ptr<ParamType> current_value_;
}; // class CartesianProductGenerator3::Iterator }; // class CartesianProductGenerator3::Iterator
// No implementation - assignment is unsupported. // No implementation - assignment is unsupported.
@ -443,7 +447,7 @@ class CartesianProductGenerator4
const typename ParamGenerator<T4>::iterator begin4_; const typename ParamGenerator<T4>::iterator begin4_;
const typename ParamGenerator<T4>::iterator end4_; const typename ParamGenerator<T4>::iterator end4_;
typename ParamGenerator<T4>::iterator current4_; typename ParamGenerator<T4>::iterator current4_;
linked_ptr<ParamType> current_value_; std::shared_ptr<ParamType> current_value_;
}; // class CartesianProductGenerator4::Iterator }; // class CartesianProductGenerator4::Iterator
// No implementation - assignment is unsupported. // No implementation - assignment is unsupported.
@ -609,7 +613,7 @@ class CartesianProductGenerator5
const typename ParamGenerator<T5>::iterator begin5_; const typename ParamGenerator<T5>::iterator begin5_;
const typename ParamGenerator<T5>::iterator end5_; const typename ParamGenerator<T5>::iterator end5_;
typename ParamGenerator<T5>::iterator current5_; typename ParamGenerator<T5>::iterator current5_;
linked_ptr<ParamType> current_value_; std::shared_ptr<ParamType> current_value_;
}; // class CartesianProductGenerator5::Iterator }; // class CartesianProductGenerator5::Iterator
// No implementation - assignment is unsupported. // No implementation - assignment is unsupported.
@ -793,7 +797,7 @@ class CartesianProductGenerator6
const typename ParamGenerator<T6>::iterator begin6_; const typename ParamGenerator<T6>::iterator begin6_;
const typename ParamGenerator<T6>::iterator end6_; const typename ParamGenerator<T6>::iterator end6_;
typename ParamGenerator<T6>::iterator current6_; typename ParamGenerator<T6>::iterator current6_;
linked_ptr<ParamType> current_value_; std::shared_ptr<ParamType> current_value_;
}; // class CartesianProductGenerator6::Iterator }; // class CartesianProductGenerator6::Iterator
// No implementation - assignment is unsupported. // No implementation - assignment is unsupported.
@ -995,7 +999,7 @@ class CartesianProductGenerator7
const typename ParamGenerator<T7>::iterator begin7_; const typename ParamGenerator<T7>::iterator begin7_;
const typename ParamGenerator<T7>::iterator end7_; const typename ParamGenerator<T7>::iterator end7_;
typename ParamGenerator<T7>::iterator current7_; typename ParamGenerator<T7>::iterator current7_;
linked_ptr<ParamType> current_value_; std::shared_ptr<ParamType> current_value_;
}; // class CartesianProductGenerator7::Iterator }; // class CartesianProductGenerator7::Iterator
// No implementation - assignment is unsupported. // No implementation - assignment is unsupported.
@ -1216,7 +1220,7 @@ class CartesianProductGenerator8
const typename ParamGenerator<T8>::iterator begin8_; const typename ParamGenerator<T8>::iterator begin8_;
const typename ParamGenerator<T8>::iterator end8_; const typename ParamGenerator<T8>::iterator end8_;
typename ParamGenerator<T8>::iterator current8_; typename ParamGenerator<T8>::iterator current8_;
linked_ptr<ParamType> current_value_; std::shared_ptr<ParamType> current_value_;
}; // class CartesianProductGenerator8::Iterator }; // class CartesianProductGenerator8::Iterator
// No implementation - assignment is unsupported. // No implementation - assignment is unsupported.
@ -1454,7 +1458,7 @@ class CartesianProductGenerator9
const typename ParamGenerator<T9>::iterator begin9_; const typename ParamGenerator<T9>::iterator begin9_;
const typename ParamGenerator<T9>::iterator end9_; const typename ParamGenerator<T9>::iterator end9_;
typename ParamGenerator<T9>::iterator current9_; typename ParamGenerator<T9>::iterator current9_;
linked_ptr<ParamType> current_value_; std::shared_ptr<ParamType> current_value_;
}; // class CartesianProductGenerator9::Iterator }; // class CartesianProductGenerator9::Iterator
// No implementation - assignment is unsupported. // No implementation - assignment is unsupported.
@ -1709,7 +1713,7 @@ class CartesianProductGenerator10
const typename ParamGenerator<T10>::iterator begin10_; const typename ParamGenerator<T10>::iterator begin10_;
const typename ParamGenerator<T10>::iterator end10_; const typename ParamGenerator<T10>::iterator end10_;
typename ParamGenerator<T10>::iterator current10_; typename ParamGenerator<T10>::iterator current10_;
linked_ptr<ParamType> current_value_; std::shared_ptr<ParamType> current_value_;
}; // class CartesianProductGenerator10::Iterator }; // class CartesianProductGenerator10::Iterator
// No implementation - assignment is unsupported. // No implementation - assignment is unsupported.

View File

@ -43,6 +43,10 @@ $var maxtuple = 10 $$ Maximum number of Combine arguments we want to support.
// GOOGLETEST_CM0001 DO NOT DELETE // GOOGLETEST_CM0001 DO NOT DELETE
#include <assert.h>
#include <memory>
#ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_
#define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_
@ -173,7 +177,7 @@ $for j [[
typename ParamGenerator<T$j>::iterator current$(j)_; typename ParamGenerator<T$j>::iterator current$(j)_;
]] ]]
linked_ptr<ParamType> current_value_; std::shared_ptr<ParamType> current_value_;
}; // class CartesianProductGenerator$i::Iterator }; // class CartesianProductGenerator$i::Iterator
// No implementation - assignment is unsupported. // No implementation - assignment is unsupported.

View File

@ -38,13 +38,13 @@
#include <ctype.h> #include <ctype.h>
#include <iterator> #include <iterator>
#include <memory>
#include <set> #include <set>
#include <tuple> #include <tuple>
#include <utility> #include <utility>
#include <vector> #include <vector>
#include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-linked_ptr.h"
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#include "gtest/gtest-printers.h" #include "gtest/gtest-printers.h"
@ -193,7 +193,7 @@ class ParamGenerator {
iterator end() const { return iterator(impl_->End()); } iterator end() const { return iterator(impl_->End()); }
private: private:
linked_ptr<const ParamGeneratorInterface<T> > impl_; std::shared_ptr<const ParamGeneratorInterface<T> > impl_;
}; };
// Generates values from a range of two comparable values. Can be used to // Generates values from a range of two comparable values. Can be used to
@ -519,9 +519,8 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase {
void AddTestPattern(const char* test_case_name, void AddTestPattern(const char* test_case_name,
const char* test_base_name, const char* test_base_name,
TestMetaFactoryBase<ParamType>* meta_factory) { TestMetaFactoryBase<ParamType>* meta_factory) {
tests_.push_back(linked_ptr<TestInfo>(new TestInfo(test_case_name, tests_.push_back(std::shared_ptr<TestInfo>(
test_base_name, new TestInfo(test_case_name, test_base_name, meta_factory)));
meta_factory)));
} }
// INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information // INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information
// about a generator. // about a generator.
@ -541,7 +540,7 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase {
virtual void RegisterTests() { virtual void RegisterTests() {
for (typename TestInfoContainer::iterator test_it = tests_.begin(); for (typename TestInfoContainer::iterator test_it = tests_.begin();
test_it != tests_.end(); ++test_it) { test_it != tests_.end(); ++test_it) {
linked_ptr<TestInfo> test_info = *test_it; std::shared_ptr<TestInfo> test_info = *test_it;
for (typename InstantiationContainer::iterator gen_it = for (typename InstantiationContainer::iterator gen_it =
instantiations_.begin(); gen_it != instantiations_.end(); instantiations_.begin(); gen_it != instantiations_.end();
++gen_it) { ++gen_it) {
@ -605,7 +604,7 @@ class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase {
const std::string test_base_name; const std::string test_base_name;
const scoped_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory; const scoped_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory;
}; };
typedef ::std::vector<linked_ptr<TestInfo> > TestInfoContainer; using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo> >;
// Records data received from INSTANTIATE_TEST_CASE_P macros: // Records data received from INSTANTIATE_TEST_CASE_P macros:
// <Instantiation name, Sequence generator creation function, // <Instantiation name, Sequence generator creation function,
// Name generator function, Source file, Source line> // Name generator function, Source file, Source line>

View File

@ -1305,13 +1305,13 @@ inline To DownCast_(From* f) { // so we only accept pointers
GTEST_INTENTIONAL_CONST_COND_PUSH_() GTEST_INTENTIONAL_CONST_COND_PUSH_()
if (false) { if (false) {
GTEST_INTENTIONAL_CONST_COND_POP_() GTEST_INTENTIONAL_CONST_COND_POP_()
const To to = NULL; const To to = nullptr;
::testing::internal::ImplicitCast_<From*>(to); ::testing::internal::ImplicitCast_<From*>(to);
} }
#if GTEST_HAS_RTTI #if GTEST_HAS_RTTI
// RTTI: debug mode only! // RTTI: debug mode only!
GTEST_CHECK_(f == nullptr || dynamic_cast<To>(f) != NULL); GTEST_CHECK_(f == nullptr || dynamic_cast<To>(f) != nullptr);
#endif #endif
return static_cast<To>(f); return static_cast<To>(f);
} }
@ -2334,12 +2334,12 @@ inline const char* GetEnv(const char* name) {
#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT
// We are on Windows CE, which has no environment variables. // We are on Windows CE, which has no environment variables.
static_cast<void>(name); // To prevent 'unused argument' warning. static_cast<void>(name); // To prevent 'unused argument' warning.
return NULL; return nullptr;
#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)
// Environment variables which we programmatically clear will be set to the // Environment variables which we programmatically clear will be set to the
// empty string rather than unset (NULL). Handle that case. // empty string rather than unset (NULL). Handle that case.
const char* const env = getenv(name); const char* const env = getenv(name);
return (env != NULL && env[0] != '\0') ? env : NULL; return (env != nullptr && env[0] != '\0') ? env : nullptr;
#else #else
return getenv(name); return getenv(name);
#endif #endif

View File

@ -731,7 +731,7 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
const TestInfo* const info = impl->current_test_info(); const TestInfo* const info = impl->current_test_info();
const int death_test_index = info->result()->death_test_count(); const int death_test_index = info->result()->death_test_count();
if (flag != NULL) { if (flag != nullptr) {
// ParseInternalRunDeathTestFlag() has performed all the necessary // ParseInternalRunDeathTestFlag() has performed all the necessary
// processing. // processing.
set_write_fd(flag->write_fd()); set_write_fd(flag->write_fd());
@ -740,8 +740,8 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
// WindowsDeathTest uses an anonymous pipe to communicate results of // WindowsDeathTest uses an anonymous pipe to communicate results of
// a death test. // a death test.
SECURITY_ATTRIBUTES handles_are_inheritable = { SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES),
sizeof(SECURITY_ATTRIBUTES), NULL, TRUE }; nullptr, TRUE};
HANDLE read_handle, write_handle; HANDLE read_handle, write_handle;
GTEST_DEATH_TEST_CHECK_( GTEST_DEATH_TEST_CHECK_(
::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,
@ -754,8 +754,8 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
&handles_are_inheritable, &handles_are_inheritable,
TRUE, // The event will automatically reset to non-signaled state. TRUE, // The event will automatically reset to non-signaled state.
FALSE, // The initial state is non-signalled. FALSE, // The initial state is non-signalled.
NULL)); // The even is unnamed. nullptr)); // The even is unnamed.
GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL); GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != nullptr);
const std::string filter_flag = const std::string filter_flag =
std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" +
info->test_case_name() + "." + info->name(); info->test_case_name() + "." + info->name();
@ -771,8 +771,7 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
"|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get())); "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));
char executable_path[_MAX_PATH + 1]; // NOLINT char executable_path[_MAX_PATH + 1]; // NOLINT
GTEST_DEATH_TEST_CHECK_( GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(nullptr,
_MAX_PATH + 1 != ::GetModuleFileNameA(NULL,
executable_path, executable_path,
_MAX_PATH)); _MAX_PATH));
@ -795,16 +794,15 @@ DeathTest::TestRole WindowsDeathTest::AssumeRole() {
startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE); startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
PROCESS_INFORMATION process_info; PROCESS_INFORMATION process_info;
GTEST_DEATH_TEST_CHECK_(::CreateProcessA( GTEST_DEATH_TEST_CHECK_(
executable_path, ::CreateProcessA(
const_cast<char*>(command_line.c_str()), executable_path, const_cast<char*>(command_line.c_str()),
NULL, // Retuned process handle is not inheritable. nullptr, // Retuned process handle is not inheritable.
NULL, // Retuned thread handle is not inheritable. nullptr, // Retuned thread handle is not inheritable.
TRUE, // Child inherits all inheritable handles (for write_handle_). TRUE, // Child inherits all inheritable handles (for write_handle_).
0x0, // Default creation flags. 0x0, // Default creation flags.
NULL, // Inherit the parent's environment. nullptr, // Inherit the parent's environment.
UnitTest::GetInstance()->original_working_dir(), UnitTest::GetInstance()->original_working_dir(), &startup_info,
&startup_info,
&process_info) != FALSE); &process_info) != FALSE);
child_handle_.Reset(process_info.hProcess); child_handle_.Reset(process_info.hProcess);
::CloseHandle(process_info.hThread); ::CloseHandle(process_info.hThread);
@ -842,9 +840,7 @@ class FuchsiaDeathTest : public DeathTestImpl {
// Utility class for accumulating command-line arguments. // Utility class for accumulating command-line arguments.
class Arguments { class Arguments {
public: public:
Arguments() { Arguments() { args_.push_back(nullptr); }
args_.push_back(NULL);
}
~Arguments() { ~Arguments() {
for (std::vector<char*>::iterator i = args_.begin(); i != args_.end(); for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();
@ -967,7 +963,7 @@ DeathTest::TestRole FuchsiaDeathTest::AssumeRole() {
const TestInfo* const info = impl->current_test_info(); const TestInfo* const info = impl->current_test_info();
const int death_test_index = info->result()->death_test_count(); const int death_test_index = info->result()->death_test_count();
if (flag != NULL) { if (flag != nullptr) {
// ParseInternalRunDeathTestFlag() has performed all the necessary // ParseInternalRunDeathTestFlag() has performed all the necessary
// processing. // processing.
set_write_fd(kFuchsiaReadPipeFd); set_write_fd(kFuchsiaReadPipeFd);
@ -1316,7 +1312,8 @@ static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {
fd_flags | FD_CLOEXEC)); fd_flags | FD_CLOEXEC));
struct inheritance inherit = {0}; struct inheritance inherit = {0};
// spawn is a system call. // spawn is a system call.
child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron()); child_pid =
spawn(args.argv[0], 0, nullptr, &inherit, args.argv, GetEnviron());
// Restores the current working directory. // Restores the current working directory.
GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1); GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);
GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd)); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));

View File

@ -101,7 +101,7 @@ FilePath FilePath::GetCurrentDir() {
return FilePath(kCurrentDirectoryString); return FilePath(kCurrentDirectoryString);
#elif GTEST_OS_WINDOWS #elif GTEST_OS_WINDOWS
char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? "" : cwd);
#else #else
char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; char cwd[GTEST_PATH_MAX_ + 1] = { '\0' };
char* result = getcwd(cwd, sizeof(cwd)); char* result = getcwd(cwd, sizeof(cwd));
@ -109,7 +109,7 @@ FilePath FilePath::GetCurrentDir() {
// getcwd will likely fail in NaCl due to the sandbox, so return something // getcwd will likely fail in NaCl due to the sandbox, so return something
// reasonable. The user may have provided a shim implementation for getcwd, // reasonable. The user may have provided a shim implementation for getcwd,
// however, so fallback only when failure is detected. // however, so fallback only when failure is detected.
return FilePath(result == NULL ? kCurrentDirectoryString : cwd); return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);
# endif // GTEST_OS_NACL # endif // GTEST_OS_NACL
return FilePath(result == nullptr ? "" : cwd); return FilePath(result == nullptr ? "" : cwd);
#endif // GTEST_OS_WINDOWS_MOBILE #endif // GTEST_OS_WINDOWS_MOBILE
@ -136,8 +136,8 @@ const char* FilePath::FindLastPathSeparator() const {
#if GTEST_HAS_ALT_PATH_SEP_ #if GTEST_HAS_ALT_PATH_SEP_
const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator); const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);
// Comparing two pointers of which only one is NULL is undefined. // Comparing two pointers of which only one is NULL is undefined.
if (last_alt_sep != NULL && if (last_alt_sep != nullptr &&
(last_sep == NULL || last_alt_sep > last_sep)) { (last_sep == nullptr || last_alt_sep > last_sep)) {
return last_alt_sep; return last_alt_sep;
} }
#endif #endif
@ -324,7 +324,7 @@ bool FilePath::CreateFolder() const {
#if GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS_MOBILE
FilePath removed_sep(this->RemoveTrailingPathSeparator()); FilePath removed_sep(this->RemoveTrailingPathSeparator());
LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str()); LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());
int result = CreateDirectory(unicode, NULL) ? 0 : -1; int result = CreateDirectory(unicode, nullptr) ? 0 : -1;
delete [] unicode; delete [] unicode;
#elif GTEST_OS_WINDOWS #elif GTEST_OS_WINDOWS
int result = _mkdir(pathname_.c_str()); int result = _mkdir(pathname_.c_str());

View File

@ -31,10 +31,11 @@
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
#include <limits.h> #include <limits.h>
#include <stdlib.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include <string.h> #include <string.h>
#include <fstream> #include <fstream>
#include <memory>
#if GTEST_OS_WINDOWS #if GTEST_OS_WINDOWS
# include <windows.h> # include <windows.h>
@ -141,7 +142,7 @@ size_t GetThreadCount() {
} }
procfs_info process_info; procfs_info process_info;
const int status = const int status =
devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL); devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), nullptr);
close(fd); close(fd);
if (status == EOK) { if (status == EOK) {
return static_cast<size_t>(process_info.num_threads); return static_cast<size_t>(process_info.num_threads);
@ -155,7 +156,7 @@ size_t GetThreadCount() {
size_t GetThreadCount() { size_t GetThreadCount() {
struct procentry64 entry; struct procentry64 entry;
pid_t pid = getpid(); pid_t pid = getpid();
int status = getprocs64(&entry, sizeof(entry), NULL, 0, &pid, 1); int status = getprocs64(&entry, sizeof(entry), nullptr, 0, &pid, 1);
if (status == 1) { if (status == 1) {
return entry.pi_thcount; return entry.pi_thcount;
} else { } else {
@ -233,15 +234,15 @@ void AutoHandle::Reset(HANDLE handle) {
bool AutoHandle::IsCloseable() const { bool AutoHandle::IsCloseable() const {
// Different Windows APIs may use either of these values to represent an // Different Windows APIs may use either of these values to represent an
// invalid handle. // invalid handle.
return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE; return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE;
} }
Notification::Notification() Notification::Notification()
: event_(::CreateEvent(NULL, // Default security attributes. : event_(::CreateEvent(nullptr, // Default security attributes.
TRUE, // Do not reset automatically. TRUE, // Do not reset automatically.
FALSE, // Initially unset. FALSE, // Initially unset.
NULL)) { // Anonymous event. nullptr)) { // Anonymous event.
GTEST_CHECK_(event_.Get() != NULL); GTEST_CHECK_(event_.Get() != nullptr);
} }
void Notification::Notify() { void Notification::Notify() {
@ -270,7 +271,7 @@ Mutex::~Mutex() {
if (type_ == kDynamic) { if (type_ == kDynamic) {
::DeleteCriticalSection(critical_section_); ::DeleteCriticalSection(critical_section_);
delete critical_section_; delete critical_section_;
critical_section_ = NULL; critical_section_ = nullptr;
} }
} }
@ -389,15 +390,15 @@ class ThreadWithParamSupport : public ThreadWithParamBase {
DWORD thread_id; DWORD thread_id;
// FIXME: Consider to use _beginthreadex instead. // FIXME: Consider to use _beginthreadex instead.
HANDLE thread_handle = ::CreateThread( HANDLE thread_handle = ::CreateThread(
NULL, // Default security. nullptr, // Default security.
0, // Default stack size. 0, // Default stack size.
&ThreadWithParamSupport::ThreadMain, &ThreadWithParamSupport::ThreadMain,
param, // Parameter to ThreadMainStatic param, // Parameter to ThreadMainStatic
0x0, // Default creation flags. 0x0, // Default creation flags.
&thread_id); // Need a valid pointer for the call to work under Win98. &thread_id); // Need a valid pointer for the call to work under Win98.
GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error " GTEST_CHECK_(thread_handle != nullptr)
<< ::GetLastError() << "."; << "CreateThread failed with error " << ::GetLastError() << ".";
if (thread_handle == NULL) { if (thread_handle == nullptr) {
delete param; delete param;
} }
return thread_handle; return thread_handle;
@ -417,7 +418,7 @@ class ThreadWithParamSupport : public ThreadWithParamBase {
static DWORD WINAPI ThreadMain(void* ptr) { static DWORD WINAPI ThreadMain(void* ptr) {
// Transfers ownership. // Transfers ownership.
scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr)); scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));
if (param->thread_can_start_ != NULL) if (param->thread_can_start_ != nullptr)
param->thread_can_start_->WaitForNotification(); param->thread_can_start_->WaitForNotification();
param->runnable_->Run(); param->runnable_->Run();
return 0; return 0;
@ -475,7 +476,7 @@ class ThreadLocalRegistryImpl {
thread_local_values thread_local_values
.insert(std::make_pair( .insert(std::make_pair(
thread_local_instance, thread_local_instance,
linked_ptr<ThreadLocalValueHolderBase>( std::shared_ptr<ThreadLocalValueHolderBase>(
thread_local_instance->NewValueForCurrentThread()))) thread_local_instance->NewValueForCurrentThread())))
.first; .first;
} }
@ -484,7 +485,7 @@ class ThreadLocalRegistryImpl {
static void OnThreadLocalDestroyed( static void OnThreadLocalDestroyed(
const ThreadLocalBase* thread_local_instance) { const ThreadLocalBase* thread_local_instance) {
std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders; std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
// Clean up the ThreadLocalValues data structure while holding the lock, but // Clean up the ThreadLocalValues data structure while holding the lock, but
// defer the destruction of the ThreadLocalValueHolderBases. // defer the destruction of the ThreadLocalValueHolderBases.
{ {
@ -512,7 +513,7 @@ class ThreadLocalRegistryImpl {
static void OnThreadExit(DWORD thread_id) { static void OnThreadExit(DWORD thread_id) {
GTEST_CHECK_(thread_id != 0) << ::GetLastError(); GTEST_CHECK_(thread_id != 0) << ::GetLastError();
std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders; std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;
// Clean up the ThreadIdToThreadLocals data structure while holding the // Clean up the ThreadIdToThreadLocals data structure while holding the
// lock, but defer the destruction of the ThreadLocalValueHolderBases. // lock, but defer the destruction of the ThreadLocalValueHolderBases.
{ {
@ -539,7 +540,8 @@ class ThreadLocalRegistryImpl {
private: private:
// In a particular thread, maps a ThreadLocal object to its value. // In a particular thread, maps a ThreadLocal object to its value.
typedef std::map<const ThreadLocalBase*, typedef std::map<const ThreadLocalBase*,
linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues; std::shared_ptr<ThreadLocalValueHolderBase> >
ThreadLocalValues;
// Stores all ThreadIdToThreadLocals having values in a thread, indexed by // Stores all ThreadIdToThreadLocals having values in a thread, indexed by
// thread's ID. // thread's ID.
typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals; typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;
@ -554,18 +556,17 @@ class ThreadLocalRegistryImpl {
HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,
FALSE, FALSE,
thread_id); thread_id);
GTEST_CHECK_(thread != NULL); GTEST_CHECK_(thread != nullptr);
// We need to pass a valid thread ID pointer into CreateThread for it // We need to pass a valid thread ID pointer into CreateThread for it
// to work correctly under Win98. // to work correctly under Win98.
DWORD watcher_thread_id; DWORD watcher_thread_id;
HANDLE watcher_thread = ::CreateThread( HANDLE watcher_thread = ::CreateThread(
NULL, // Default security. nullptr, // Default security.
0, // Default stack size 0, // Default stack size
&ThreadLocalRegistryImpl::WatcherThreadFunc, &ThreadLocalRegistryImpl::WatcherThreadFunc,
reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)), reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),
CREATE_SUSPENDED, CREATE_SUSPENDED, &watcher_thread_id);
&watcher_thread_id); GTEST_CHECK_(watcher_thread != nullptr);
GTEST_CHECK_(watcher_thread != NULL);
// Give the watcher thread the same priority as ours to avoid being // Give the watcher thread the same priority as ours to avoid being
// blocked by it. // blocked by it.
::SetThreadPriority(watcher_thread, ::SetThreadPriority(watcher_thread,
@ -685,7 +686,7 @@ void RE::Init(const char* regex) {
// Returns true iff ch appears anywhere in str (excluding the // Returns true iff ch appears anywhere in str (excluding the
// terminating '\0' character). // terminating '\0' character).
bool IsInSet(char ch, const char* str) { bool IsInSet(char ch, const char* str) {
return ch != '\0' && strchr(str, ch) != NULL; return ch != '\0' && strchr(str, ch) != nullptr;
} }
// Returns true iff ch belongs to the given classification. Unlike // Returns true iff ch belongs to the given classification. Unlike
@ -739,7 +740,7 @@ static std::string FormatRegexSyntaxError(const char* regex, int index) {
// Generates non-fatal failures and returns false if regex is invalid; // Generates non-fatal failures and returns false if regex is invalid;
// otherwise returns true. // otherwise returns true.
bool ValidateRegex(const char* regex) { bool ValidateRegex(const char* regex) {
if (regex == NULL) { if (regex == nullptr) {
// FIXME: fix the source file location in the // FIXME: fix the source file location in the
// assertion failures to match where the regex is used in user // assertion failures to match where the regex is used in user
// code. // code.
@ -865,8 +866,7 @@ bool MatchRegexAtHead(const char* regex, const char* str) {
// exponential with respect to the regex length + the string length, // exponential with respect to the regex length + the string length,
// but usually it's must faster (often close to linear). // but usually it's must faster (often close to linear).
bool MatchRegexAnywhere(const char* regex, const char* str) { bool MatchRegexAnywhere(const char* regex, const char* str) {
if (regex == NULL || str == NULL) if (regex == nullptr || str == nullptr) return false;
return false;
if (*regex == '^') if (*regex == '^')
return MatchRegexAtHead(regex + 1, str); return MatchRegexAtHead(regex + 1, str);
@ -899,8 +899,8 @@ bool RE::PartialMatch(const char* str, const RE& re) {
// Initializes an RE from its string representation. // Initializes an RE from its string representation.
void RE::Init(const char* regex) { void RE::Init(const char* regex) {
pattern_ = full_pattern_ = NULL; pattern_ = full_pattern_ = nullptr;
if (regex != NULL) { if (regex != nullptr) {
pattern_ = posix::StrDup(regex); pattern_ = posix::StrDup(regex);
} }
@ -1257,8 +1257,8 @@ bool BoolFromGTestEnv(const char* flag, bool default_value) {
#else #else
const std::string env_var = FlagToEnvVar(flag); const std::string env_var = FlagToEnvVar(flag);
const char* const string_value = posix::GetEnv(env_var.c_str()); const char* const string_value = posix::GetEnv(env_var.c_str());
return string_value == NULL ? return string_value == nullptr ? default_value
default_value : strcmp(string_value, "0") != 0; : strcmp(string_value, "0") != 0;
#endif // defined(GTEST_GET_BOOL_FROM_ENV_) #endif // defined(GTEST_GET_BOOL_FROM_ENV_)
} }
@ -1271,7 +1271,7 @@ Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) {
#else #else
const std::string env_var = FlagToEnvVar(flag); const std::string env_var = FlagToEnvVar(flag);
const char* const string_value = posix::GetEnv(env_var.c_str()); const char* const string_value = posix::GetEnv(env_var.c_str());
if (string_value == NULL) { if (string_value == nullptr) {
// The environment variable is not set. // The environment variable is not set.
return default_value; return default_value;
} }
@ -1314,7 +1314,7 @@ const char* StringFromGTestEnv(const char* flag, const char* default_value) {
#else #else
const std::string env_var = FlagToEnvVar(flag); const std::string env_var = FlagToEnvVar(flag);
const char* const value = posix::GetEnv(env_var.c_str()); const char* const value = posix::GetEnv(env_var.c_str());
return value == NULL ? default_value : value; return value == nullptr ? default_value : value;
#endif // defined(GTEST_GET_STRING_FROM_ENV_) #endif // defined(GTEST_GET_STRING_FROM_ENV_)
} }

View File

@ -423,9 +423,6 @@ void AssertHelper::operator=(const Message& message) const {
); // NOLINT ); // NOLINT
} }
// Mutex for linked pointers.
GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);
// A copy of all command line arguments. Set by InitGoogleTest(). // A copy of all command line arguments. Set by InitGoogleTest().
static ::std::vector<std::string> g_argvs; static ::std::vector<std::string> g_argvs;
@ -905,11 +902,10 @@ TimeInMillis GetTimeInMillis() {
// value using delete[]. Returns the wide string, or NULL if the // value using delete[]. Returns the wide string, or NULL if the
// input is NULL. // input is NULL.
LPCWSTR String::AnsiToUtf16(const char* ansi) { LPCWSTR String::AnsiToUtf16(const char* ansi) {
if (!ansi) return NULL; if (!ansi) return nullptr;
const int length = strlen(ansi); const int length = strlen(ansi);
const int unicode_length = const int unicode_length =
MultiByteToWideChar(CP_ACP, 0, ansi, length, MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);
NULL, 0);
WCHAR* unicode = new WCHAR[unicode_length + 1]; WCHAR* unicode = new WCHAR[unicode_length + 1];
MultiByteToWideChar(CP_ACP, 0, ansi, length, MultiByteToWideChar(CP_ACP, 0, ansi, length,
unicode, unicode_length); unicode, unicode_length);
@ -922,13 +918,12 @@ LPCWSTR String::AnsiToUtf16(const char* ansi) {
// value using delete[]. Returns the ANSI string, or NULL if the // value using delete[]. Returns the ANSI string, or NULL if the
// input is NULL. // input is NULL.
const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { const char* String::Utf16ToAnsi(LPCWSTR utf16_str) {
if (!utf16_str) return NULL; if (!utf16_str) return nullptr;
const int ansi_length = const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,
WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, 0, nullptr, nullptr);
NULL, 0, NULL, NULL);
char* ansi = new char[ansi_length + 1]; char* ansi = new char[ansi_length + 1];
WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr,
ansi, ansi_length, NULL, NULL); nullptr);
ansi[ansi_length] = 0; ansi[ansi_length] = 0;
return ansi; return ansi;
} }
@ -1730,7 +1725,7 @@ AssertionResult HRESULTFailureHelper(const char* expr,
0, // no line width restrictions 0, // no line width restrictions
error_text, // output buffer error_text, // output buffer
kBufSize, // buf size kBufSize, // buf size
NULL); // no arguments for inserts nullptr); // no arguments for inserts
// Trims tailing white space (FormatMessage leaves a trailing CR-LF) // Trims tailing white space (FormatMessage leaves a trailing CR-LF)
for (; message_length && IsSpace(error_text[message_length - 1]); for (; message_length && IsSpace(error_text[message_length - 1]);
--message_length) { --message_length) {
@ -2402,7 +2397,7 @@ namespace internal {
static std::string FormatCxxExceptionMessage(const char* description, static std::string FormatCxxExceptionMessage(const char* description,
const char* location) { const char* location) {
Message message; Message message;
if (description != NULL) { if (description != nullptr) {
message << "C++ exception with description \"" << description << "\""; message << "C++ exception with description \"" << description << "\"";
} else { } else {
message << "Unknown C++ exception"; message << "Unknown C++ exception";
@ -2500,7 +2495,7 @@ Result HandleExceptionsInMethodIfSupported(
} catch (...) { // NOLINT } catch (...) { // NOLINT
internal::ReportFailureInUnknownLocation( internal::ReportFailureInUnknownLocation(
TestPartResult::kFatalFailure, TestPartResult::kFatalFailure,
FormatCxxExceptionMessage(NULL, location)); FormatCxxExceptionMessage(nullptr, location));
} }
return static_cast<Result>(0); return static_cast<Result>(0);
#else #else
@ -3676,8 +3671,7 @@ static bool PortableLocaltime(time_t seconds, struct tm* out) {
// MINGW <time.h> provides neither localtime_r nor localtime_s, but uses // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses
// Windows' localtime(), which has a thread-local tm buffer. // Windows' localtime(), which has a thread-local tm buffer.
struct tm* tm_ptr = localtime(&seconds); // NOLINT struct tm* tm_ptr = localtime(&seconds); // NOLINT
if (tm_ptr == NULL) if (tm_ptr == nullptr) return false;
return false;
*out = *tm_ptr; *out = *tm_ptr;
return true; return true;
#else #else
@ -4732,11 +4726,11 @@ void UnitTest::AddTestPartResult(
// with clang/gcc we can achieve the same effect on x86 by invoking int3 // with clang/gcc we can achieve the same effect on x86 by invoking int3
asm("int3"); asm("int3");
#else #else
// Dereference NULL through a volatile pointer to prevent the compiler // Dereference nullptr through a volatile pointer to prevent the compiler
// from removing. We use this rather than abort() or __builtin_trap() for // from removing. We use this rather than abort() or __builtin_trap() for
// portability: Symbian doesn't implement abort() well, and some debuggers // portability: Symbian doesn't implement abort() well, and some debuggers
// don't correctly trap abort(). // don't correctly trap abort().
*static_cast<volatile int*>(NULL) = 1; *static_cast<volatile int*>(nullptr) = 1;
#endif // GTEST_OS_WINDOWS #endif // GTEST_OS_WINDOWS
} else if (GTEST_FLAG(throw_on_failure)) { } else if (GTEST_FLAG(throw_on_failure)) {
#if GTEST_HAS_EXCEPTIONS #if GTEST_HAS_EXCEPTIONS
@ -6028,7 +6022,7 @@ std::string TempDir() {
return "\\temp\\"; return "\\temp\\";
#elif GTEST_OS_WINDOWS #elif GTEST_OS_WINDOWS
const char* temp_dir = internal::posix::GetEnv("TEMP"); const char* temp_dir = internal::posix::GetEnv("TEMP");
if (temp_dir == NULL || temp_dir[0] == '\0') if (temp_dir == nullptr || temp_dir[0] == '\0')
return "\\temp\\"; return "\\temp\\";
else if (temp_dir[strlen(temp_dir) - 1] == '\\') else if (temp_dir[strlen(temp_dir) - 1] == '\\')
return temp_dir; return temp_dir;

View File

@ -1,151 +0,0 @@
// Copyright 2003, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <stdlib.h>
#include "gtest/internal/gtest-linked_ptr.h"
#include "gtest/gtest.h"
namespace {
using testing::Message;
using testing::internal::linked_ptr;
int num;
Message* history = nullptr;
// Class which tracks allocation/deallocation
class A {
public:
A(): mynum(num++) { *history << "A" << mynum << " ctor\n"; }
virtual ~A() { *history << "A" << mynum << " dtor\n"; }
virtual void Use() { *history << "A" << mynum << " use\n"; }
protected:
int mynum;
};
// Subclass
class B : public A {
public:
B() { *history << "B" << mynum << " ctor\n"; }
~B() { *history << "B" << mynum << " dtor\n"; }
virtual void Use() { *history << "B" << mynum << " use\n"; }
};
class LinkedPtrTest : public testing::Test {
public:
LinkedPtrTest() {
num = 0;
history = new Message;
}
virtual ~LinkedPtrTest() {
delete history;
history = nullptr;
}
};
TEST_F(LinkedPtrTest, GeneralTest) {
{
linked_ptr<A> a0, a1, a2;
// Use explicit function call notation here to suppress self-assign warning.
a0.operator=(a0);
a1 = a2;
ASSERT_EQ(a0.get(), static_cast<A*>(nullptr));
ASSERT_EQ(a1.get(), static_cast<A*>(nullptr));
ASSERT_EQ(a2.get(), static_cast<A*>(nullptr));
ASSERT_TRUE(a0 == nullptr);
ASSERT_TRUE(a1 == nullptr);
ASSERT_TRUE(a2 == nullptr);
{
linked_ptr<A> a3(new A);
a0 = a3;
ASSERT_TRUE(a0 == a3);
ASSERT_TRUE(a0 != nullptr);
ASSERT_TRUE(a0.get() == a3);
ASSERT_TRUE(a0 == a3.get());
linked_ptr<A> a4(a0);
a1 = a4;
linked_ptr<A> a5(new A);
ASSERT_TRUE(a5.get() != a3);
ASSERT_TRUE(a5 != a3.get());
a2 = a5;
linked_ptr<B> b0(new B);
linked_ptr<A> a6(b0);
ASSERT_TRUE(b0 == a6);
ASSERT_TRUE(a6 == b0);
ASSERT_TRUE(b0 != nullptr);
a5 = b0;
a5 = b0;
a3->Use();
a4->Use();
a5->Use();
a6->Use();
b0->Use();
(*b0).Use();
b0.get()->Use();
}
a0->Use();
a1->Use();
a2->Use();
a1 = a2;
a2.reset(new A);
a0.reset();
linked_ptr<A> a7;
}
ASSERT_STREQ(
"A0 ctor\n"
"A1 ctor\n"
"A2 ctor\n"
"B2 ctor\n"
"A0 use\n"
"A0 use\n"
"B2 use\n"
"B2 use\n"
"B2 use\n"
"B2 use\n"
"B2 use\n"
"B2 dtor\n"
"A2 dtor\n"
"A0 use\n"
"A0 use\n"
"A1 use\n"
"A3 ctor\n"
"A0 dtor\n"
"A3 dtor\n"
"A1 dtor\n",
history->GetString().c_str());
}
} // Unnamed namespace

View File

@ -121,7 +121,7 @@ TEST_F(TestPartResultTest, type) {
// Tests TestPartResult::file_name(). // Tests TestPartResult::file_name().
TEST_F(TestPartResultTest, file_name) { TEST_F(TestPartResultTest, file_name) {
EXPECT_STREQ("foo/bar.cc", r1_.file_name()); EXPECT_STREQ("foo/bar.cc", r1_.file_name());
EXPECT_STREQ(NULL, r3_.file_name()); EXPECT_STREQ(nullptr, r3_.file_name());
EXPECT_STREQ("foo/bar.cc", r4_.file_name()); EXPECT_STREQ("foo/bar.cc", r4_.file_name());
} }

View File

@ -33,7 +33,6 @@
// Sometimes it's desirable to build most of Google Test's own tests // Sometimes it's desirable to build most of Google Test's own tests
// by compiling a single file. This file serves this purpose. // by compiling a single file. This file serves this purpose.
#include "test/googletest-filepath-test.cc" #include "test/googletest-filepath-test.cc"
#include "test/googletest-linked-ptr-test.cc"
#include "test/googletest-message-test.cc" #include "test/googletest-message-test.cc"
#include "test/googletest-options-test.cc" #include "test/googletest-options-test.cc"
#include "test/googletest-port-test.cc" #include "test/googletest-port-test.cc"

View File

@ -6181,16 +6181,9 @@ TEST_F(FlagfileTest, Empty) {
std::string flagfile_flag = std::string flagfile_flag =
std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
const char* argv[] = { const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
"foo.exe",
flagfile_flag.c_str(),
NULL
};
const char* argv2[] = { const char* argv2[] = {"foo.exe", nullptr};
"foo.exe",
NULL
};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false); GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);
} }
@ -6202,16 +6195,9 @@ TEST_F(FlagfileTest, FilterNonEmpty) {
std::string flagfile_flag = std::string flagfile_flag =
std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
const char* argv[] = { const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
"foo.exe",
flagfile_flag.c_str(),
NULL
};
const char* argv2[] = { const char* argv2[] = {"foo.exe", nullptr};
"foo.exe",
NULL
};
GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false); GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter("abc"), false);
} }
@ -6225,16 +6211,9 @@ TEST_F(FlagfileTest, SeveralFlags) {
std::string flagfile_flag = std::string flagfile_flag =
std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str(); std::string("--" GTEST_FLAG_PREFIX_ "flagfile=") + flagfile_path.c_str();
const char* argv[] = { const char* argv[] = {"foo.exe", flagfile_flag.c_str(), nullptr};
"foo.exe",
flagfile_flag.c_str(),
NULL
};
const char* argv2[] = { const char* argv2[] = {"foo.exe", nullptr};
"foo.exe",
NULL
};
Flags expected_flags; Flags expected_flags;
expected_flags.break_on_failure = true; expected_flags.break_on_failure = true;