以下代码: https: //godbolt.org/z/eYEdTnMqc
#include<memory>
#include<vector>
#include<string>
class Base {
protected:
std::string type;
};
class Derived1 : public Base{
protected:
bool status;
public:
Derived1(): status(false), type("Derived1") {}
void setStatus(bool newStatus) {
status = newStatus;
}
bool getStatus() {
return status;
}
};
int main() {
std::vector<std::shared_ptr<Base>> vars;
vars.push_back(std::make_shared<Derived1>());
if(!vars.back()->getStatus()) {
vars.back()->setStatus(true);
}
}
Run Code Online (Sandbox Code Playgroud)
给我这个编译错误:
Could not execute the program
Compiler returned: 1
Compiler stderr
<source>: In constructor 'Derived1::Derived1()':
<source>:13:32: error: class 'Derived1' does not have any field named 'type'
13 | …
Run Code Online (Sandbox Code Playgroud) 我正在尝试std::unique_ptr
类继承(即多态性)。我正在运行的代码如下:
#include<iostream>
#include<memory>
class polygon {
public:
int side;
polygon(int i): side(i) {std::cout<<"polygon created"<<std::endl;}
virtual int perimeter() = 0;
~polygon() {std::cout<<"polygon destroyed"<<std::endl;}
};
class triangle : public polygon {
public:
triangle(int i): polygon::polygon{i} {std::cout<<"triangle created"<<std::endl;}
int perimeter() { return side*3; }
~triangle() {std::cout<<"triangle destroyed"<<std::endl;}
};
class square : public polygon {
public:
square(int i): polygon::polygon{i} {std::cout<<"square created"<<std::endl;}
int perimeter() { return side*4; }
~square() {std::cout<<"square destroyed"<<std::endl;}
};
int main() {
std::unique_ptr<polygon> pp = std::make_unique<square>(5); // (1)
std::cout << …
Run Code Online (Sandbox Code Playgroud) 我想定义两个类A
,并I
以它们的对象尊重这种关系的方式:
i1 -----------a1
|------a2
|----a3
Run Code Online (Sandbox Code Playgroud)
该类的一个实例I
指向该类的零个、一个或多个实例A
。
类的一个实例A
仅指向该类的一个实例I
。
类的实例I
可以没有任何类的实例A
,但类的实例必须“附加”A
类的实例。I
为了满足这些条件,我将这两个类声明如下:
class I;
class A
{
private:
std::string as;
std::shared_ptr<I> iA;
public:
A(std::string aTxt);
A();
~A();
};
class I
{
private:
std::string ip;
std::vector<std::unique_ptr<A>> as;
friend class A;
public:
I(std::string i);
~I();
};
Run Code Online (Sandbox Code Playgroud)
在源文件中,我以这种方式定义了这两个类:
A::A(std::string aText)
{
as = aText;
}
A::A()
{
as = "";
}
A::~A()
{
}
I::I(std::string i)
{ …
Run Code Online (Sandbox Code Playgroud) 既然你可以做到std::unique_ptr<int> upi{new int}
,我立即对如何为什么std::unique_ptr<int*> upi{new int[42]{}}
不起作用感到困惑.有人可以解释以下片段之间的区别吗?
{
std::unique_ptr<int> upi{new int[42]{}};
upi.get()[0];
}
// Doesn't work
{
std::unique_ptr<int> upi{new int[42]{}};
upi[0];
}
{
std::unique_ptr<int[]> upi{new int[42]{}};
upi.get()[0];
}
{
std::unique_ptr<int[]> upi{new int[42]{}};
upi[0];
}
// Doesn't work
{
std::unique_ptr<int*> upi{new int[42]{}};
upi.get()[0];
}
// Doesn't work
{
std::unique_ptr<int*> upi{new int[42]{}};
upi[0];
}
Run Code Online (Sandbox Code Playgroud)
编译器错误:
prog.cpp: In function ‘int main()’:
prog.cpp:8:20: warning: value computed is not used [-Wunused-value]
upi.get()[0];
^
prog.cpp:14:12: error: no match for ‘operator[]’ (operand types are ‘std::unique_ptr<int>’ …
Run Code Online (Sandbox Code Playgroud) 目前我有 C++ 代码(我使用的是 Visual Studio 2013):
char * dest= new char[srcLen + 1] {};
strcpy(dest, source);
std::string s(dest);
delete dest;
Run Code Online (Sandbox Code Playgroud)
如何将其转换为 C++11以便可以unique_ptr
使用?make_unique
strcpy()
我试过:
auto dest = make_unique<char>(srcLen + 1);
strcpy(dest, source);
Run Code Online (Sandbox Code Playgroud)
但是,我收到以下编译strcpy
错误
Error 1 error C2664: 'char *strcpy(char *,const char *)' : cannot convert argument 1 from 'std::unique_ptr<char,std::default_delete<char>>' to 'char *'
Run Code Online (Sandbox Code Playgroud)
更新我确实使用了std::string
. 我已经更新了我的代码片段以使其更加清晰。基本上,源 char * 数组可能会也可能不会以 null 结尾。临时dest
缓冲区确保字符串以空字符结尾。我确实想将其转换为std::string
. 我之前的作品有效。我只是想知道是否有一种方法可以使用创建临时缓冲区,make_unique
这样就不需要new
和delete
。
我对现代C++不太熟悉,希望更好地理解以下片段:
State & m_rootstate;
//...
auto currstate = std::make_unique<State> (m_rootstate);
do_something (*currstate);
// currstate is not used anywhere else
Run Code Online (Sandbox Code Playgroud)
我看到a unique_ptr
是从对a的引用创建的State
.这应该使用copy ctor State
来创建一个新实例State
,并指向这个新实例的指针currstate
.
currstate
然后立即取消引用作为函数的参数.currstate
之后没有使用,但是在调用完成之后它不会超出范围,所以它和它的链接State
不会过早被破坏.
对于调用,使用其中的值unique_ptr
.取决于是否do_something
采取State
或State&
,它将被再次复制.
这是正确的吗?如果是这样,是否正确的目的unique_ptr
只是创建一个副本m_rootstate
而不必担心内存管理?
当我使用重置重新绑定时unique_ptr
,发生了一些不好的事情,但是当使用时std::make_unique
,一切正常。
int main() {
unique_ptr<string> p= nullptr;
auto l=[&p]()->void{
static string x {"1111"};
cout<<x<<endl;
//p = std::make_unique<string>(x);// compile ok
p.reset(&x);//compile error free():invalid pointer;
cout<<p.get()<<endl;
return;
};
l();
cout<<p->length()<<endl;
cout<<p.get()<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我认为当调用reset方法时,字符串对象并没有真正交给管理unique_ptr
。当离开作用域时,dtor 被调用两次
我正在尝试使用带有c ++的SDL2库,因此,某些函数需要一个指向SDL_Window或SDL_Renderer的双指针.我为一个SDL_Window设置了一些内存并将其赋予一个如此独特的指针:
window = unique_ptr<SDL_Window, decltype(free) *>
reinterpret_cast<SDL_Window *>(malloc(sizeof(SDL_Window))),
free};
Run Code Online (Sandbox Code Playgroud)
我使用以下网站作为指南:http://www.codeproject.com/Articles/820931/Using-std-unique-ptr-RAII-with-malloc-and-free
所以现在我需要一个指向存储在unique_ptr中的指针的指针,但是我很难这样做.我尝试过这样的事情:
&window.get()
// or
&&(*window)
// or
&window
// and even
&(&(*(window.get())))
Run Code Online (Sandbox Code Playgroud)
所有这些都导致奇怪的编译器错误,例如一元'&'运算符需要l值,这对于第一个和最后一个案例是完全可以理解的.
更新 我现在还使用原始SDL_Window*来获取unique_ptr的地址和.我的一些代码片段(虽然脱离了上下文):
SDL_Window *window_ptr;
unique_ptr<SDL_Window> window;
window = unique_ptr<SDL_Window, decltype(SDL_DestroyWindow)> (
window_ptr,
SDL_DestroyWindow);
SDL_CreateWindowAndRenderer(500, 500, SDL_WINDOW_SHOWN, &window_ptr, &renderer_ptr);
Run Code Online (Sandbox Code Playgroud)
但现在,我正在运行此编译器错误:
/usr/include/c++/5/bits/unique_ptr.h:272:18: error: no match for ‘operator=’
(operand types are ‘std::unique_ptr<SDL_Window>::deleter_type
{aka std::default_delete<SDL_Window>}’ and ‘void (*)(void*)’)
get_deleter() = std::forward<_Ep>(__u.get_deleter());
Run Code Online (Sandbox Code Playgroud) 我刚刚在一个情况下稳定了一个unique_pointer引用作为函数参数传递.所以我看一下它,发现代码实际上是在编译和运行.
为什么会这样?当你可以引用那个指针时,指针是如何唯一的?
这是我的例子:
class Foo{
public:
int bar{23};
};
void Bar(std::unique_ptr<Foo>& a_foo){
a_foo->bar = 42;
}
int main(int argc, char *argv[]){
auto foo{ std::make_unique<Foo>() };
Bar(foo);
std::cout << foo->bar << std::endl; //outputs 42
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我有一个函数将unique_ptr返回给数组元素,我注意到原始变量没有得到更新.
为什么这样做(a [5] = = 6 after):
int a[10];
for (size_t i = 0; i < 10; i++)
{
a[i] = i;
}
int* ap = &a[5];
*ap += 1;
Run Code Online (Sandbox Code Playgroud)
但
int a[10];
for (size_t i = 0; i < 10; i++)
{
a[i] = i;
}
unique_ptr<int> ap = make_unique<int>(a[5]);
*ap += 1;
Run Code Online (Sandbox Code Playgroud)
不更新原始数组元素?(a [5] == 5):
多次赋值unique_ptr<T>
有效吗?根据输出,确实如此,但是当使用 且返回值被分配给已经持有现有内存的aT
时,是否保证调用 的析构函数?make_unique()
unique_ptr
#include <iostream>
#include <string>
#include <memory>
class A{
public:
A(){ std::cout << "Construcor" << std::endl; }
~A(){ std::cout << "Destrucor" << std::endl; }
void foo(){ std::cout << "foo" << std::endl; }
};
int main()
{
std::unique_ptr<A> pointer;
for(auto i = 0; i < 2; ++i){
pointer = std::make_unique<A>();
pointer->foo();
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Construcor
foo
Construcor
Destrucor // Destructor is called because first instance of A is out of scope?
foo
Destrucor
Run Code Online (Sandbox Code Playgroud) 考虑智能指针的以下用法std::unique_ptr
:
std::unique_ptr<char> sp(new(std::nothrow) char[sz]);
Run Code Online (Sandbox Code Playgroud)
我如何检查是否new
成功?
我有两个选择:
if(!sp){}
if(sp==nullptr){}
#include <iostream>
#include <memory>
using namespace std;
int main() {
constexpr long long sz = 1000000e10;
//raw pointer
auto ptr = new(std::nothrow) char[sz];
if(ptr==nullptr)
{
cout<<"ptr nullptr"<<endl;
}
//smart pointer
std::unique_ptr<char> sp(new(std::nothrow) char[sz]);
if(!sp)
{
cout<<"sp nullptr bool"<<endl;
}
if(sp==nullptr)
{
cout<<"sp nullptr =="<<endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
std::unique_ptr<char> sp(new(std::nothrow) char[sz]);
Run Code Online (Sandbox Code Playgroud)
显然,方法 1 和方法 …
unique-ptr ×12
c++ ×11
c++11 ×5
pointers ×2
arrays ×1
c++14 ×1
new-operator ×1
polymorphism ×1
shared-ptr ×1