将一个共享指针分配给另一个共享指针是否会释放后者管理的内存?让
typedef shared_ptr<char> char_ptr_t;
char_ptr_t pA(new char('A'));
char_ptr_t pB(new char('B'));
Run Code Online (Sandbox Code Playgroud)
现在,下面的语句是否释放了 'A'?
/*1*/ pA = pB;
Run Code Online (Sandbox Code Playgroud)
还是我需要明确释放它:
/*2*/ pA.reset();
/*3*/ pA = pB;
Run Code Online (Sandbox Code Playgroud)
并且,以下代码对于实现相同是否有效?
/*4*/ pA.reset(pB); //<-- is this valid? Not compiling in MSVC++ 2010, though the standard seems to allow it.
Run Code Online (Sandbox Code Playgroud) 我试图特别了解模板和变量模板.考虑一下:
template<int M, int N>
const int gcd1 = gcd1<N, M % N>;
template<int M>
const int gcd1<M, 0> = M;
std::cout << gcd1<9, 6> << "\n";
Run Code Online (Sandbox Code Playgroud)
它打印0出错了.但是,如果我使用constexpr而不是const上面,我会得到正确的答案3.我再次得到结构模板的正确答案:
template<int M, int N>
struct gcd2 {
static const int value = gcd2<N, M % N>::value;
};
template<int M>
struct gcd2<M, 0> {
static const int value = M;
};
std::cout << gcd2<9, 6>::value << "\n";
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
编辑:
gcd1编译正常,没有基本案例专业化.怎么会?我正在使用Visual Studio 2015.
可能和很多人一样,我输入了这个错字
int a = 0;
cout << a < " "; //note the '<'
Run Code Online (Sandbox Code Playgroud)
但是,MSVC++编译器只发出警告
警告C4552:'<':运算符无效; 预期的操作员有副作用
虽然我预计会出现编译错误.它确实是标准的投诉代码吗?是否发生了使代码有效的隐式类型转换或重载?我也很困惑<运算符是将字符串" "与整数a或结果进行比较cout << a
相关的SO帖子就在这里.
为什么(@)下面的代码中没有编译错误?我认为lamb是一个左值,所以它不会被绑定到右值参考.
using FunctionType = std::function<void()>;
using IntType = int;
struct Foo {
void bar(FunctionType&&) {}
void baz(IntType&&) {}
};
Foo foo;
foo.bar([]() {}); //OK
auto lamb = []() {};
foo.bar(lamb); //(@) No compilation error?!
foo.baz(5); //OK
int i = 5;
foo.baz(i); //Error
Run Code Online (Sandbox Code Playgroud)