1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/win/scoped_comptr.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/win/scoped_com_initializer.h"
11 #include "testing/gtest/include/gtest/gtest.h"
19 Dummy() : adds(0), releases(0) { }
20 void AddRef() { ++adds
; }
21 void Release() { ++releases
; }
27 extern const IID dummy_iid
;
28 const IID dummy_iid
= {0x12345678u
,
31 {01, 23, 45, 67, 89, 01, 23, 45}};
35 TEST(ScopedComPtrTest
, ScopedComPtr
) {
36 EXPECT_EQ(memcmp(&ScopedComPtr
<IUnknown
>::iid(), &IID_IUnknown
, sizeof(IID
)),
39 base::win::ScopedCOMInitializer com_initializer
;
40 EXPECT_TRUE(com_initializer
.succeeded());
42 ScopedComPtr
<IUnknown
> unk
;
43 EXPECT_TRUE(SUCCEEDED(unk
.CreateInstance(CLSID_ShellLink
)));
44 ScopedComPtr
<IUnknown
> unk2
;
45 unk2
.Attach(unk
.Detach());
46 EXPECT_TRUE(unk
.get() == NULL
);
47 EXPECT_TRUE(unk2
.get() != NULL
);
49 ScopedComPtr
<IMalloc
> mem_alloc
;
50 EXPECT_TRUE(SUCCEEDED(CoGetMalloc(1, mem_alloc
.Receive())));
52 ScopedComPtr
<IUnknown
> qi_test
;
53 EXPECT_HRESULT_SUCCEEDED(mem_alloc
.QueryInterface(IID_IUnknown
,
54 reinterpret_cast<void**>(qi_test
.Receive())));
55 EXPECT_TRUE(qi_test
.get() != NULL
);
58 // test ScopedComPtr& constructor
59 ScopedComPtr
<IMalloc
> copy1(mem_alloc
);
60 EXPECT_TRUE(copy1
.IsSameObject(mem_alloc
.get()));
61 EXPECT_FALSE(copy1
.IsSameObject(unk2
.get())); // unk2 is valid but different
62 EXPECT_FALSE(copy1
.IsSameObject(unk
.get())); // unk is NULL
64 IMalloc
* naked_copy
= copy1
.Detach();
65 copy1
= naked_copy
; // Test the =(T*) operator.
66 naked_copy
->Release();
69 EXPECT_FALSE(copy1
.IsSameObject(unk2
.get())); // unk2 is valid, copy1 is not
71 // test Interface* constructor
72 ScopedComPtr
<IMalloc
> copy2(static_cast<IMalloc
*>(mem_alloc
.get()));
73 EXPECT_TRUE(copy2
.IsSameObject(mem_alloc
.get()));
75 EXPECT_TRUE(SUCCEEDED(unk
.QueryFrom(mem_alloc
.get())));
76 EXPECT_TRUE(unk
.get() != NULL
);
78 EXPECT_TRUE(unk
.get() == NULL
);
79 EXPECT_TRUE(unk
.IsSameObject(copy1
.get())); // both are NULL
82 TEST(ScopedComPtrTest
, ScopedComPtrVector
) {
83 // Verify we don't get error C2558.
84 typedef ScopedComPtr
<Dummy
, &dummy_iid
> Ptr
;
85 std::vector
<Ptr
> bleh
;
87 scoped_ptr
<Dummy
> p(new Dummy
);
90 EXPECT_EQ(p
->adds
, 1);
91 EXPECT_EQ(p
->releases
, 0);
93 EXPECT_EQ(p
->adds
, 2);
94 EXPECT_EQ(p
->releases
, 0);
96 EXPECT_EQ(p
->adds
, 3);
97 EXPECT_EQ(p
->releases
, 1);
98 // To avoid hitting a reallocation.
101 EXPECT_EQ(p
->adds
, 4);
102 EXPECT_EQ(p
->releases
, 1);
103 EXPECT_EQ(bleh
[0].get(), p
.get());
105 EXPECT_EQ(p
->adds
, 4);
106 EXPECT_EQ(p
->releases
, 2);
108 EXPECT_EQ(p
->adds
, 4);
109 EXPECT_EQ(p
->releases
, 4);